jessica smith
jessica smith

Reputation: 111

Find position of all unique elements in array

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);

Upvotes: 0

Views: 976

Answers (4)

Stuart
Stuart

Reputation: 9858

Use a set to record numbers that have already been seen, and add the index to an array if it has not been see.

function uniqueIndices(arr) {
    const seen = new Set();
    const indices = [];
    for (const [i, n] of arr.entries()) {
        if (!seen.has(n)) {
            seen.add(n);
            indices.push(i);
        }
    }
    return indices;
}

This also works well as a generator:

function *uniqueIndices(arr) { 
    const seen = new Set(); 
    for (const [i, n] of arr.entries()) { 
        if (!seen.has(n)) { 
            seen.add(n);
            yield i;
        }
    } 
}
console.log([...uniqueIndices([7, 9, 30, 40, 50, 8, 1, 2, 3, 40, 90,2, 88,1])])

Upvotes: 2

Scott Sauyet
Scott Sauyet

Reputation: 50797

A simple function which iterates the list just once, storing the value and index in a Map, simply testing whether it's already there before adding a new one:

const uniqueIndices = (xs) =>
  [...xs .reduce ((found, x, i) => found .has (x) ? found : found .set (x, i), new Map()) .values ()]

const arr = [7, 9, 30, 40, 50, 8, 1, 2, 3, 40, 90, 2, 88, 1]

console .log (uniqueIndices (arr))
.as-console-wrapper {max-height: 100% !important; top: 0}

Upvotes: 1

Andreas
Andreas

Reputation: 21881

.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);

Upvotes: 2

0stone0
0stone0

Reputation: 43983

  1. Get all the unique values
  2. 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
]

Upvotes: 0

Related Questions