Last active
July 15, 2020 15:00
-
-
Save jsdaniell/2ace3bcd6ab6552f3b09e2aa4c5e4239 to your computer and use it in GitHub Desktop.
Using find(); to filter with javascript (First way)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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