3

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?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.