讓 arr = [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 游樂場保存了此代碼。
問題:我正在嘗試獲取陣列中唯一元素的所有索引。我已經嘗試了下面的代碼來獲取 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);
uj5u.com熱心網友回復:
.indexOf()將始終回傳第一個匹配項的索引。如果我們將它與 a 結合起來,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);
uj5u.com熱心網友回復:
- 獲取所有唯一值
- 映射要
indexOf在原始陣列上使用的唯一元素以獲取唯一元素的索引
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
]
uj5u.com熱心網友回復:
使用集合記錄已經看過的數字,如果沒有看到則將索引添加到陣列中。
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;
}
uj5u.com熱心網友回復:
一個簡單的函式,它只迭代一次串列,將值和索引存盤在 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}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/462137.html
標籤:javascript html 数组 算法 排序
