Webber Depor Webber Depor - 2 months ago 9
Javascript Question

Choose if array element repeats itself twice -- Javascript

There is a javascript array

var arr = [0, 1, 2, 2, 3, 3, 5];


I want to choose elements that repeats twice. In this case its
2
and
3
. and i want attach them into a variable.

var a = 2, b = 3;


As far as i know there is no built-in function to do that job. How can i do that. Thanks.

Answer

You can use filter to get the values that occur twice.

var arr  = [0, 1, 2, 2, 3, 3, 5];

var dups = arr.filter ( (v,i,a) => a.indexOf(v) < i );

console.log(dups);

In comments you stated you would only have doubles, but no values that occur more than twice. Note that the above would return a value more than once, if the latter would be the case.

This returns the values in an array, which is how you should work. To put them in separate values can be done as follows:

var [a, b, ...others] = dups;

...but you would have to know how many variables to reserve for that, and it does not make your further program any easier. JavaScript has many nice functions (methods) for arrays, so you should in fact leave them in an array.