Skip to content

Instantly share code, notes, and snippets.

@larrybolt
Last active September 23, 2016 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save larrybolt/8e51cd8f32f931e76a7be27805498ea7 to your computer and use it in GitHub Desktop.
Save larrybolt/8e51cd8f32f931e76a7be27805498ea7 to your computer and use it in GitHub Desktop.
// Let's say we have an array of candy
var all_candy = [
{
name: 'Mars',
price: 1,
category: 'chocolate'
},
{
name: 'Snickers',
price: 1.1,
category: 'Chocolate'
},
{
name: 'Bounty',
price: 1,
category: 'chocolate'
},
{
name: 'Leo',
price: .8,
category: 'Waffer'
},
{
name: 'Ole',
price: .4,
category: 'Waffer',
fake: true
},
{
name: 'VegiBlah',
price: 3.4,
category: 'Misc',
fake: false
},
];
/* yes that's valid javascript, the last objects in the array are
a bit different, it's one of the reason javascript is terrible, because that sort of stuff is so common and possible
*/
// let's say we are cheap and we want a cheap_candy array (price<1
// for that we would need to loop trough all elements of the array, right?
var cheap_candy = [];
for (var i = 0; i < all_candy.length; i++) {
if (all_candy[i].price < 1) cheap_candy.push(all_candy[i]);
}
// or we use filter
var cheap_candy = candy.filter(function(candy){
return candy.price < 1;
});
// since ES6 they added a shorthand, so this works too:
var cheap_candy = candy.filter(c => c.price < 1);
/*
consult the docs about filter:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
*/
/*
there are a lot of different array iteration methods such as:
forEach, entries, every, some, filter, find, findIndex, keys,
map, reduce, reduceRight, values
The most important one is reduce, because reduce can be made into doing the
safe stuff as others, for instance to do the filter bit of candies with reduce:
*/
var cheap_candy = all_candy.reduce((previous, current) => {
if (current.price < 1) previous.push(current)
return previous;
, []);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment