Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

js: create an array that holds the indexof duplicates in array

I'm looking for a js/jquery solution for the following

I want to check an array for duplicates, lets say:

var destRes = ['BH17 7EP', 'TA2 6LL', 'OX15 4LJ', 'OX15 4LJ', 'OX15 4LJ', 'BH17 7EP', 'TA2 6LL']

and return an array that holds the first index of that value; for example for the above ex this should be the return:

var newArr = ['0', '1', '2', '2', '2', '0', '1' ]

BH17 7EP is at index 0 and 5, so in the new array the 0 and the 5 indexes should be 0, the first instance of BH17 7EP

TA2 6LL is at index 1 and 6 so in the new array the 1 and the 6 indexes should be 1, the first instance of TA2 6LL

like image 609
florinescu Avatar asked Jan 19 '26 10:01

florinescu


1 Answers

you can iterate over the array and use indexOf() it always returns the first index of a value in the array. something like this:

var destRes = ['BH17 7EP', 'TA2 6LL', 'OX15 4LJ', 'OX15 4LJ', 'OX15 4LJ', 'BH17 7EP', 'TA2 6LL'];

var indexes = destRes.map(x => destRes.indexOf(x));

console.log(indexes);
like image 166
Dij Avatar answered Jan 20 '26 23:01

Dij



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!