I have an array like this:
var arr = [a,a,b,b,b,c]
The result(a new array) should only show all the values which are exactly 2 times in this array, e.g.: a
Do you guys know how I could realize this? Thanks
I have an array like this:
var arr = [a,a,b,b,b,c]
The result(a new array) should only show all the values which are exactly 2 times in this array, e.g.: a
Do you guys know how I could realize this? Thanks
You can first create object and add properties with forEach
loop and then use filter
on Object.keys
to return array as result.
var arr = ['a','a','b','b','b','c'];
var o = {}
arr.forEach(e => o[e] = (o[e] || 0) + 1);
var result = Object.keys(o).filter(e => o[e] == 2);
console.log(result)
Please try this code:
var arr = ['a','a','b','b','b','c'];
var numberOfOccurrences = {};
arr.forEach(function (item) {
numberOfOccurrences[item] = (numberOfOccurrences[item] || 0) + 1;
});
var duplicates = Object.keys(numberOfOccurrences).filter(function (item) { return numberOfOccurrences[item] === 2 });
console.log(duplicates);