How can I get all the indexes based on a condition for an array of objects? I have tried the code below, but it's returning only the first occurrence.
a = [
{prop1:"abc",prop2:"yutu"},
{prop1:"bnmb",prop2:"yutu"},
{prop1:"zxvz",prop2:"qwrq"}];
index = a.findIndex(x => x.prop2 ==="yutu");
console.log(index);
CodePudding user response:
findIndex
will return only one matching index, You can check value against property prop2
using filter
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);
CodePudding user response:
Try 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);
CodePudding user response:
You can use normal for loop and when ever the prop2
matches push the index in the array
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);
CodePudding user response:
The
findIndex
method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test. - MDN
You can use reduce
here:
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);
CodePudding user response:
You can simply iterate through objects, e.g.
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);
CodePudding user response:
You can directly use filter
without map function
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);