Skip to content

Instantly share code, notes, and snippets.

@jsdaniell
Last active July 15, 2020 15:00
Show Gist options
  • Select an option

  • Save jsdaniell/2ace3bcd6ab6552f3b09e2aa4c5e4239 to your computer and use it in GitHub Desktop.

Select an option

Save jsdaniell/2ace3bcd6ab6552f3b09e2aa4c5e4239 to your computer and use it in GitHub Desktop.
Using find(); to filter with javascript (First way)
const dataToFilter = ['Blue', 'White', 'Red', 'Yellow'];
let filteredBlueItem = dataToFilter.find(item => item === 'Blue');
console.log(filteredBlueItem)
// Blue
let filteredBlackItem = dataToFilter.find(item => item === 'Black');
console.log(filteredBlackItem);
// undefined
function findCreator(comparisonItem, key) {
return (i) => i[key] === comparisonItem;
}
let items = [{id: 1, color: 'Blue'}, {id: 2, color: 'Red'}, {id: 3, color: 'Black'}];
let matchedItem = items.find(findCreator('Red', 'color'));
console.log(matchedItem);
// {id: 2, color: "Red"}
let secondMatchedItem = items.find(findCreator(3, 'id'));
console.log(secondMatchedItem);
// {id: 3, color: "Black"}
function finderFunction(item) {
return item.id === this.id;
}
let list = [{id: 1}, {id: 2}, {id: 3}];
let found = list.find(finderFunction, {id: 2});
console.log(found);
// {id: 2}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment