ES6 Object array looks for an object

The way to find a particular element of an array is findIndex()

Usage and Definitions:

  • The findIndex() method returns the position of the first element in an array that is passed a test condition (function)
  • The findIndex() method calls the function once for each element in the array. When the element in the array returns true when testing the condition, findexIndex() returns the index position of the element that matches the condition. Subsequent values are not called again and the function is executed if there are no elements that match the condition- 1

That’s the official definition of FindIndex()

Here’s my explanation of findIndex() with an example

When the conditional returns true, findIndex pops up and returns the index of the current element.

// The first is a normal array

var dataArr = [1.2.3.4.5.6.7.8.9.0];

function fn(num, numIndex, nums){
    // The function takes three arguments, num for the current item, numIndex for the subscript of the current item, and nums for the array.
    return num > 5;
}

dataArr.findIndex(fn);// the value is 5(6 subscript)-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- line -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --// Similarly suppose your array is an array of objects:
var objArr = [{
    name: 'wang'.age: 14}, {name: 'the king'.age: 41}, {name: 'Lao wang'.age: 61
}]

function objFn(obj, objIndex, objs){
    return num.age > 20;
}

objArr .findIndex(objFn);// the value is 1.
Copy the code

Findindex returns only the index of the first element that matches the criteria, so after finding the first element that matches the criteria, it will break out of the function. After finding the first element, it will not call any other elements in the array.

Practical usage examples

Let’s say we have to pick a team from all of them, but we don’t want to repeat it. So when we look by id, we can write this

var allPeple = [{
    name: 'wang'.id: 14}, {name: 'the king'.id: 41}, {name: 'Lao wang'.id: 61
}]
                
var myTeamArr = [{
    name: 'wang'.id: 14
}]
                
var PId = 14; // If this is the ID of the person to add

function pFn(p){returnp.id == PId ; }If ==-1 means no, add him to myteam. If ==-1, add him to myteam

myTeamArr.findIndex(pFn) == -1 ? myTeamArr.push(allPeple.find(pFn)) : alert('This person already exists');

// This will sum up the two for loops into a single line of code
Copy the code

One more thing to add

The equivalent, find(), uses the same thing, except that it returns the element itself, not its index.

compatibility

Since it is for ES6, be careful with compatibility issues when using it. Ie11 and earlier versions are not compatible.