Skip to content

Instantly share code, notes, and snippets.

@6ui11em
Last active April 2, 2018 20:21
Show Gist options
  • Save 6ui11em/50a75599e990cffb93c05210dc5933ed to your computer and use it in GitHub Desktop.
Save 6ui11em/50a75599e990cffb93c05210dc5933ed to your computer and use it in GitHub Desktop.
Javascript find / search in array #javascript #js
var original = [1, 2, 7, 42, 99, 101];
// Get items bigger than 10
var biggerThanTen = original.filter(function (item) {
return item > 10;
});
// Get items smaller than 10
var smallerThanTen = original.filter(function (item) {
if (item < 10) {
return true;
}
});
// Logs [42, 99, 101]
console.log(biggerThanTen);
// Logs [1, 2, 7]
console.log(smallerThanTen);
// With find
var sandwiches = ['turkey', 'chicken salad', 'tuna', 'pb&j', 'egg salad'];
var getTuna = sandwiches.find(function (sandwich) {
return sandwich === 'tuna';
});
// Logs "tuna"
console.log(getTuna);
var todos = [
{
item: 'Wash the dog',
added: 2018-03-22,
completed: false
},
{
item: 'Plan surprise party for Bailey',
added: 2018-03-14,
completed: false
},
{
item: 'Go see Black Panther',
added: 2018-03-12,
completed: true
},
{
item: 'Launch a podcast',
added: 2018-03-05,
completed: false
}
];
var item = todos.find(function (todo) {
return todo.item === 'Go see Black Panther';
});
// every
// Returns true
[12, 25, 42, 99, 101].every(function (item) {
return item > 10;
});
// Returns false
[1, 12, 25, 42, 99, 101].every(function (item) {
return item > 10;
});
// some
// Returns true
[12, 25, 42, 99, 101].some(function (item) {
return item > 10;
});
// Returns true
[1, 12, 25, 42, 99, 101].some(function (item) {
return item > 10;
});
// Returns false
[1, 1, 3, 7, 9, 10].some(function (item) {
return item > 10;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment