【问题标题】:Find all index based on condition根据条件查找所有索引
【发布时间】:2022-01-16 03:33:57
【问题描述】:
如何根据对象数组的条件获取所有索引?
我试过下面的代码,但它只返回第一次出现。
a = [
{prop1:"abc",prop2:"yutu"},
{prop1:"bnmb",prop2:"yutu"},
{prop1:"zxvz",prop2:"qwrq"}];
index = a.findIndex(x => x.prop2 ==="yutu");
console.log(index);
【问题讨论】:
标签:
javascript
arrays
vue.js
【解决方案1】:
你可以直接使用filter不带地图功能
const a = [
{ prop1: "abc", prop2: "yutu" },
{ prop1: "bnmb", prop2: "yutu" },
{ prop1: "zxvz", prop2: "qwrq" },
];
const res = a.filter((item) => {
return item.prop2==="yutu";
});
console.log(res);
【解决方案2】:
您可以简单地遍历对象,例如
function getIndexes(hystack, nameOfProperty, needle) {
const res = new Array();
for (const [i, item] of hystack.entries()) {
if (item[nameOfProperty] === needle) res.push(i);
}
return res;
}
const items =
[
{prop1:"a", prop2:"aa"},
{prop1:"b", prop2:"bb"},
{prop1:"c", prop2:"aa"},
{prop1:"c", prop2:"bb"},
{prop1:"d", prop2:"cc"}
];
const indexes = getIndexes(items, 'prop2', 'bb');
console.log('Result', indexes);
【解决方案3】:
findIndex 将只返回一个匹配索引,您可以使用filter 来检查属性prop2 的值
a = [
{prop1:"abc",prop2:"yutu"},
{prop1:"bnmb",prop2:"yutu"},
{prop1:"zxvz",prop2:"qwrq"}];
const allIndexes = a
.map((e, i) => e.prop2 === 'yutu' ? i : -1)
.filter(index => index !== -1);
console.log(allIndexes);
// This is one liner solution might not work in older IE ('flatMap')
const notSupportedInIE =a.flatMap((e, i) => e.prop2 === 'yutu' ? i : []);
console.log(notSupportedInIE);
【解决方案4】:
findIndex 方法返回第一个元素的索引
满足提供的测试功能的数组。否则,它
返回 -1,表示没有元素通过测试。 -MDN
你可以在这里使用reduce:
const a = [
{ prop1: "abc", prop2: "yutu" },
{ prop1: "bnmb", prop2: "yutu" },
{ prop1: "zxvz", prop2: "qwrq" },
];
const result = a.reduce((acc, curr, i) => {
if (curr.prop2 === "yutu") acc.push(i);
return acc;
}, []);
console.log(result);
【解决方案5】:
您可以使用普通的 for 循环,当 prop2 匹配时,将索引推送到数组中
const a = [{
prop1: "abc",
prop2: "yutu"
},
{
prop1: "bnmb",
prop2: "yutu"
},
{
prop1: "zxvz",
prop2: "qwrq"
}
];
const indArr = [];
for (let i = 0; i < a.length; i++) {
if (a[i].prop2 === 'yutu') {
indArr.push(i)
}
}
console.log(indArr);
【解决方案6】:
试试Array.reduce
a = [
{prop1:"abc",prop2:"yutu"},
{prop1:"bnmb",prop2:"yutu"},
{prop1:"zxvz",prop2:"qwrq"}];
index = a.reduce((acc, {prop2}, index) => prop2 ==="yutu" ? [...acc, index] : acc, []);
console.log(index);