d t
d t

Reputation: 33

How to find element in array

I'm really new to javascript and I have an array of objects.

var cart = [
  { id: 1, price: 2 },
  { id: 2, price: 1 }
];

and I'm using a for loop to find the ID:

for (var i = 0; i < cart.length; i++) {
  if (cart[i].id === id) {
    return cart[i]
  }
}

return null;

I know there's functions like find(), but I'm not too sure on how to use that. Can anyone help?

Upvotes: 3

Views: 89

Answers (2)

Oscar Franco
Oscar Franco

Reputation: 6260

With find, you might need babel, but just the code you need:

ES6

const id = 1;
const found = cart.find(item => item.id === id)

Vanilla

var id = 1;
var found = cart.find(function(item) {return item.id === id})

find takes a function (in our case with es6: () => {} is an anonymous function), and applies it to every item in the list, until it finds the first match, how does it know when it is a match: once your function returns true, then it cuts the loop, and returns the item.

HOWEVER

Another option, that does not use find but might be more readable than a traditional for loop:

var id = 1;
for(var item in cart) {
  if(item.id == id) {
    return item;
  }
}
return null

There are also a slew of libraries out there that can help you achieve this on different ways, ex: underscore.js, lodash, which I will not cover, but you can take a look at if you are really interested.

Upvotes: 5

random_user_name
random_user_name

Reputation: 26180

You are right. There is a function called find. You can set up the callback function to use with find, and even set it up to accept a parameter (such as the id):

var cart = [{
  id: 1,
  price: 2
}, {
  id: 2,
  price: 1
}];

function byID(id) {
  return function(element) {
    return element.id == id;
  }
}

var item = cart.find(byID(2));

console.log(item);

With issues like this, I very much appreciate the library lodash. It allows you to do things like so:

var cart = [{id: 1, price: 5}, {id: 2, price: 6}];

var item = _.find(cart, {id:2});

console.log(item);
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

Upvotes: 4

Related Questions