Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialElizabeth Chai
9,692 Pointsis there a way to use .indexOf to find an object's value in an array?
for example,
var things= [
{item: "chocolate", price: "3.45"},
{item: "coffee", price: "3.45"},
{item: "bread", price: "3.45"},
{item: "chips", price: "3.45"}
];
how would you use .indexOf to find "chocolate" or "chips" or even the price? I tried to look this up on MDN but sometimes it's hard to understand the explanations... thanks so much.
2 Answers
Neil McPartlin
14,662 PointsHi Elizabeth,
Using indexOf would have been feasible had your array only contained primitive types such as numbers, strings etc. but as your array contains objects, it needs a different approach.
Array.prototype.findIndex()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
So for example, this will work.
things.findIndex(i => i.item === "chips"); // 3
Then having found that chips is located at index 3, the price is found like so.
things[3].price; // '3.45'
But as suggested by James, 'find' may suit your needs better.
Array.prototype.find()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
So for this, we first need a simple callback which includes the searched item
function search(things) {
return things.item === 'chips';
}
Now run this
things.find(search) // { item: 'chips', price: '3.45' }
So with this method, we are not told the index, but we do find the other 'key:value' located at the same index.
james south
Front End Web Development Techdegree Graduate 33,271 PointsindexOf just gets the first index, if you want the value of an element try the find method.