I had a chance to teach about arrays in PHP, so how was Javascript?I thought, I tried to summarize.
Retrieve only a specific element of an array
Use array.filter
. Returns an array by filtering only the elements that meet the specified criteria.
Using
let animal= ['pig', 'cow', 'pig', 'lion', 'cat']; let animalPig = animal.filter(function(n){ return n === 'pig' }); // If you write in the Arrow function let animalPig = animal.filter(n => n === 'pig'); // ['pig', 'pig']
For object
let animal= [ { name: 'pig', num: '2'}, { name: 'cow', num: '4'}, { name: 'pig', num: '3'}, { name: 'lion', num: '2'}, { name: 'cat', num: '1'}, ]; let animalNumTwo = matches.filter(n => n.num === '2'); // outputed object // [ // { name: 'pig', num: '2'}, // { name: 'lion', num: '2'}, // ];
It can also be used to count the number of specific elements in an array in an application.
// Count how many pigs there are let animal= ['pig', 'cow', 'pig', 'lion', 'cat']; let count = animal.filter(n => n === 'pig').length; // count === 2
Find a specific element in an array
array.find
Returns the value of the first element in the array that satisfies the condition.
Using
let numbers = [7, 120, 40, 33, 150]; let number = numbers.find(n => n > 100); // number === 120
Determines whether all elements in the array meet the condition
Use array.every
.If all elements meet the condition, it is true
, and if not satisfied, it returns false
.
Note: every
returns true for an empty array.
Using
var isLimit = (n) => n < 10; let numbers = [1, 8, 9, 5]; console.log(numbers.every(isLimit)); // true
For example, check whether the date is set, etc.
let isDateTime = eventList.every(value => value.datetime); //true if eventList element datetime has a value
Determine whether an array contains a specific element
Use array.includes
.Returns true
if a particular element is contained in an array, false
if it is not.
Using
let animal= ['pig', 'cow', 'pig', 'lion', 'cat']; console.log(animal.includes('cat')); // true
Find out if there are any elements in the array that meet the conditions
Use array.some
.Returns true
when any one element of the array satisfies the condition.
Note: some
returns false
for empty arrays.
Using
let numbers = [1, 8, 9, 5]; let isEven = (n) => n % 2 === 0; // true because there are 8
The difference between includes and some?
Includes
simply determines whether a particular element is included.
Some
can determine whether certain conditions (functions can be used) are met.
If you want to find a simple array, includes is simple.
If you want to find a specific value from an associative array or object, you may want to use some and use a function.