user8966479
user8966479

Reputation:

Find the first object in array

I have an array like this:

const array = [
    {
        id: "1",
        value: "alpha"
    },
    {
        id: "2",
        value: "beta"
    },
    {
        id: "3",
        value: "beta"
    },
    {   
        id: "4",
        value: "omega"
    }
];

I need a method that returns only the first object that meets my criteria in this case the attribute value.

I wrote this method with a loop:

findObject(array, value) {
    for(let i = 0; i < array.length; i++) {
         if(array[i].value === value) {
             return i;
         }
    }
    return -1;
}

Is there any way to do it without the loop? Thank you.

Upvotes: 2

Views: 59

Answers (2)

user8950389
user8950389

Reputation:

In ES 5 you can also use this.

var index = array.findIndex(function(item){return item.value === value};     
console.log(index);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

You could use Array#findIndex for the index with a callback.

const
    array = [{ id: "1", value: "alpha" }, { id: "2", value: "beta" }, { id: "3", value: "beta" }, { id: "4", value: "omega" }],
    value = 'beta',
    index = array.findIndex(o => o.value === value);
    
console.log(index);

For the item, you could use Array#find.

const
    array = [{ id: "1", value: "alpha" }, { id: "2", value: "beta" }, { id: "3", value: "beta" }, { id: "4", value: "omega" }],
    value = 'beta',
    item = array.find(o => o.value === value);
    
console.log(item);

Upvotes: 4

Related Questions