let arrr = [7, 9, 30, 40, 50, 8, 1, 2, 3, 40, 90,2, 88,1];
output=[0, 1, 2, 3, 4, 5, 6, 7, 8 ,10, 12 ]
I saved this code at javascript playground here.
Question: I am trying to get all the index of unique elements in array. I have tried the code below to get the unqiue array but i do not know how to extract its index to give the expected output as above.
let ar = [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 2, 1];
let unique = ar.filter((value, index) => {
return ar.indexOf(value) == index;
});
console.log(unique);
CodePudding user response:
.indexOf()
will always return the index of the first match. If we combine that with a Set
we get the expected output:
let input = [7, 9, 30, 40, 50, 8, 1, 2, 3, 40, 90, 2, 88, 1];
const indices = input.map(el => input.indexOf(el));
const output = new Set(indices);
const output_as_array = [...output]; // if you need an actual array
console.log(output_as_array);
CodePudding user response:
- Get all the unique values
- Map over the uniques to use
indexOf
on the original array to get the indexes of the uniques
let arrr = [7, 9, 30, 40, 50, 8, 1, 2, 3, 40, 90,2, 88,1];
let unique = arrr.filter((v, i, a) => a.indexOf(v) === i);
let uniquesIndexes = unique.map(u => arrr.indexOf(u));
console.log(uniquesIndexes)
Output:
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
10,
12
]