What's wrong with this JavaScript Code (Arrays)? -
below code snippet finds out "how many times each element of array repeated". working expected except doesn't give me "ebay repetition count"
var strarr = ["google","ebay","yahoo","google","ebay","facebook","facebook","google"]; var output= {}; strarr.foreach(function(element) { var count = 0; try{ while(strarr.indexof(element) !== -1){ strarr.splice(strarr.indexof(element),1); count++; } }catch(e){ console.log(e); } output[element] = count; }); console.log(output);
i tried debugging debugger;
, figured out second element of array being skipped.
expected output:
google:3 ebay:2 yahoo:1 facebook:2
actual output:
google:3 yahoo:1 facebook:2
- foreach take google index 0:
- you removed google list including zero
- foreach moves index 1 has yahoo ebay moved index 0
sorry bad english
Comments
Post a Comment