我可以找到一個陣列是否存在于另一個陣列中:
const arr1 = [[1,2,3],[2,2,2],[3,2,1]];
const match = [2,2,2];
// Does match exist
const exists = arr1.some(item => {
return item.every((num, index) => {
return match[index] === num;
});
});
我可以找到該陣列的索引:
let index;
// Index of match
for(let x = 0; x < arr1.length; x ) {
let result;
for(let y = 0; y < arr1[x].length; y ) {
if(arr1[x][y] === match[y]) {
result = true;
} else {
result = false;
break;
}
}
if(result === true) {
index = x;
break;
}
}
但是是否可以使用 JS 的高階函式找到索引?我看不到類似的問題/答案,它只是在語法上更簡潔一些
謝謝
uj5u.com熱心網友回復:
你可以帶Array#findIndex。
const
array = [[1, 2, 3], [2, 2, 2], [3, 2, 1]],
match = [2, 2, 2],
index = array.findIndex(inner => inner.every((v, i) => match[i] === v));
console.log(index);
uj5u.com熱心網友回復:
另一種方法將inner-arraysof 陣列轉換為字串['1,2,3', '2,2,2', '3,2,1'],并將匹配的陣列轉換為 string 2,2,2。然后使用內置函式indexOf在陣列中搜索該索引。
const arr1 = [[1,2,3],[2,2,2],[3,2,1]];
const match = [2,2,2];
const arr1Str = arr1.map(innerArr=>innerArr.toString());
const index = arr1Str.indexOf(match.toString())
console.log(index);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/371799.html
標籤:javascript 数组 高阶函数
上一篇:用Java從陣列中洗掉一個數字
