I have an array like this : [‘a’, ‘a’, ‘b’, ‘c’, ‘a’ ]
I want to obtain this : [0, 0, 1, 2, 0]
The idea is to give the first value of the arr1 array 0 value, the second 1, etc…
I tried this :
function onlyUnique(value, index, array) {
return array.indexOf(value) === index;
}
let arr1 = ['a', 'a', 'b', 'c', 'a' ]
var arr1_uniq= arr1.filter(onlyUnique);
let k=0
var list = []
for (let i in arr1_uniq){
list.push(k)
k++
}
So I have the arr1 without duplicate : [‘a’, ‘b’, ‘c’] And the corresponding values : [0, 1, 2]
And finally I tried to use the findIndex function to reallocate arr1 values but I have issues.
3
Answers
It should be possible by mapping the values to its unique index like this:
You can use a
Map<Object, Number>
and a counter to keep track of the indices.You can remove the need for the
currIndex
if you utilize thesize
property of the map.Here it is in one line:
And now, the code golf:
Here is the desired code sample using
Map
: