How To Find The Number Of Equal Elements In Javascript Array
I'm new to JavaScript so please help me on this problem: I have array and I want to get the number of same values. My array is: var arr = ['red', 'blue', 'green', 'red', 'red', 'g
Solution 1:
You can reduce the array to a hash map to figure out how many of each word there are:
var words = ["red", "blue", "green", "red", "red", "gray"];
var wordCounts = words.reduce(function(counts, word) {
counts[word] = (counts[word] || 0)++;
}, { });
console.log(wordCounts);
// >> {// red: 3,// blue: 1,// green: 1,// gray: 1// }
If you want the name of any words that are duplicated, you can filter the original array down:
var repeatedWords = words.filter(function(word) {
return wordCounts[word] > 1;
});
console.log(repeatedWords);
// >> ['red']
Solution 2:
Here you've used one loop and checked your current value with it's previous value. But you need actually two loops.
First one will pick a value. And second one will match the picked value with all others. I've used a found
flag that checks if a duplicate value has already been found or not. Try this way,
var numberOfSameElements = 0;
var found = false;
var arr = ["red", "blue", "green", "red", "red", "gray"];
for(var i = 0 ; i <arr.length;i++){
for(var j = 0; j < arr.length; j++){
if(arr[i] === arr[j] && i != j){
if(!found){
numberOfSameElements++;
found = true;
}
}
}
found = false;
}
console.log(numberOfSameElements);
Solution 3:
If you want to get the max number of duplicates find in the array, you first have to count them all. Then find the maximum repetition number (fiddle):
functiongetLargestNumberOfSame(arr) {
var counterMap = arr.reduce(function (sameMap, item) { // create a map of same valuesif (!sameMap[item]) {
sameMap[item] = 1;
} else {
sameMap[item]++;
}
return sameMap;
}, {});
var maxValues = Object.keys(counterMap).map(function(key) { // turn the map into array of max valuesreturn counterMap[key];
});
returnMath.max.apply(window, maxValues); // return the maximum value
}
Solution 4:
var numberOfSameElements = 1;
var arr = ["red", "blue", "green", "red", "red", "gray"];
arr = arr.sort();
var last;
for(var i = 0 ; i <arr.length -1 ;i++) {
//console.log(arr[i],arr[i+1]);if(arr[i] == arr[i+1]){
numberOfSameElements++;
last = arr[i];
} else {
console.log(arr[i],"repert",numberOfSameElements,"times");
numberOfSameElements=1;
}
}
console.log(last,"repert",numberOfSameElements,"times");
Post a Comment for "How To Find The Number Of Equal Elements In Javascript Array"