Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all index based on condition

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);
like image 441
Manu Avatar asked Dec 12 '21 06:12

Manu


People also ask

How do you find the index of list elements that meet a condition in Python?

In Python to find a position of an element in a list using the index() method and it will search an element in the given list and return its index.

How do you find the range of indexes in Python?

Python range() is a built-in function available with Python from Python(3. x), and it gives a sequence of numbers based on the start and stop index given. In case the start index is not given, the index is considered as 0, and it will increment the value by 1 till the stop index.

How do you get the indices of all occurrences of an element in a list in Python?

One of the most basic ways to get the index positions of all occurrences of an element in a Python list is by using a for loop and the Python enumerate function. The enumerate function is used to iterate over an object and returns both the index and element.

How do I find the index of a specific element?

To find the index of an element in a list, you use the index() function. It returns 3 as expected.

How to get index of all rows whose particular column satisfies condition?

np.where () Method to Get Index of All Rows Whose Particular Column Satisfies Given Condition np.where () takes condition as an input and returns the indices of elements that satisfy the given condition. Hence, we could use np.where () to get indices of all rows whose particular column satisfies the given condition.

How to use index match with multiple criteria?

Here's the generic INDEX MATCH formula with multiple criteria in rows and columns: Table_array - the map or area to search within, i.e. all data values excluding column and rows headers. Vlookup_value - the value you are looking for vertically in a column. Lookup_column - the column range to search in, usually the row headers.

How to get indices of all rows whose particular columns satisfy condition in pandas?

pandas.DataFrame.query () to Get Indices of All Rows Whose Particular Column Satisfies Given Condition pandas.DataFrame.query () returns DataFrame resulting from the provided query expression. Now, we can use the index attribute of DataFrame to return indices of all the rows whose particular column satisfies the given condition.

How to use the index function in Excel?

You can follow along if you select cell A19, go to tab "Formulas" on the ribbon and press with left mouse button on the "Evaluate Formula" button. The INDEX function is mostly used for getting a single value from a given cell range, however, it can also return an entire column or row from a cell range.


6 Answers

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);
like image 130
manikant gautam Avatar answered Oct 21 '22 01:10

manikant gautam


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);
like image 3
ProGu Avatar answered Oct 21 '22 01:10

ProGu


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);
like image 3
brk Avatar answered Oct 21 '22 02:10

brk


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);
like image 2
decpk Avatar answered Oct 21 '22 01:10

decpk


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);
like image 2
Boštjan Biber Avatar answered Oct 21 '22 01:10

Boštjan Biber


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);
like image 1
Amaarrockz Avatar answered Oct 21 '22 01:10

Amaarrockz