Skip to content
Advertisement

How Do I return the index of an object in an array -Javascript

How can I return the index of an object based on the key value in the object if the objects are in an array like the following.

[{"fruit":"apple", "color":"red"},{"fruit":"orange", color: "orange"},{"fruit":"kiwi", color: "green"}]

//expected output for apple is 0
//expected output for orange is 1
//expected output for kiwi is 2

Advertisement

Answer

You can user findIndex

const arr = [{"fruit":"apple", "color":"red"},{"fruit":"orange", color: "orange"},{"fruit":"kiwi", color: "green"}];

console.log(arr.findIndex(x => x.fruit === "apple"))
console.log(arr.findIndex(x => x.fruit === "orange"))
console.log(arr.findIndex(x => x.fruit === "kiwi"))

If you have to search with same prop over and over again you can create a separate function for that.

const arr = [{"fruit":"apple", "color":"red"},{"fruit":"orange", color: "orange"},{"fruit":"kiwi", color: "green"}];

const findByFruit = (arr, fruit) => arr.findIndex(x => x.fruit === fruit)

console.log(findByFruit(arr, 'apple'))
console.log(findByFruit(arr, 'orange'))
console.log(findByFruit(arr, 'kiwi'))
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement