查找数组中所有唯一元素的位置

Find position of all unique elements in array

让arrr = [7, 9, 30, 40, 50, 8, 1, 2, 3, 40, 90,2, 88,1];

输出=[0, 1, 2, 3, 4, 5, 6, 7, 8 ,10, 12 ]

我将此代码保存在 javascript 游乐场 here

问题:我正在尝试获取数组中唯一元素的所有索引。我已尝试使用下面的代码来获取 unqiue 数组,但我不知道如何提取其索引以提供上述预期输出。

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

  1. Get all the unique values
  2. 映射 uniques 以在原始数组上使用 indexOf 来获取 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)


输出:

[
  0,
  1,
  2,
  3,
  4,
  5,
  6,
  7,
  8,
  10,
  12
]

.indexOf() 将始终 return 第一个匹配项的索引。如果我们将它与 Set 结合起来,我们会得到预期的输出:

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

用集合记录已经见过的数,没见过的就把索引加入数组

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

这也可以很好地用作生成器:

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

一个简单的函数,它只迭代列表一次,将值和索引存储在 Map 中,在添加新的之前简单地测试它是否已经存在:

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}