-4

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

Faizy
  • 299
  • 2
  • 12

2 Answers2

0

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)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0

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);
mgajic
  • 109
  • 6
  • Thanks. Works perfect. Could you explain me what the "?" does? Never saw it before. – Faizy Jan 11 '17 at 14:35
  • It is the ternary operator, actually, it is a short form of the if-else statement. It has the following form: "condition ? execute if the condition is true : execute if the condition is false". You can read more it about here: http://javascript.about.com/od/byexample/a/ternary-example.htm – mgajic Jan 11 '17 at 14:52
  • I've just edited the code above, so it is much shorter now, since I used JavaScript functions for filtering and itterating through the array. If you have any questions about the new code, feel free to ask me and I will explain. – mgajic Jan 11 '17 at 15:01