Explain the common traversal methods of arrays

Keywords: node.js React Celery Attribute less


This paper mainly introduces the common traversal methods of arrays: forEvery, map, filter, find, every, some, reduce. They have one thing in common: they do not change the original array.

1. forEach: Traversing arrays

var colors = ["red","blue","green"];
// ES5 traversal array method
for(var i = 0; i < colors.length; i++){ 
 console.log(colors[i]);//red blue green
// ES6 forEach
 console.log(color);//red blue green

Let's look at another example: traversing the values in an array and calculating the sum.

var numbers = [1,2,3,4,5];
var sum = 0;

map: Mapping an array to another array

map handles each element of the array by specifying a function and returns the processed new array. map does not change the original array.

The difference between forEach and map is that forEach has no return value.
map needs to return a value. If not, undefined is returned by default

Use scenario 1
Assuming that there is a numerical array (A), the values in the A array are doubled into the B array.

var numbers = [1,2,3];
var doubledNumbers = [];
// es5
for(var i = 0; i < numbers.length; i++){
 doubledNumbers.push(numbers[i] * 2);
// es6 map method
var doubled = numbers.map(function(number){
   return number * 2;

Use scenario 2 to assume that there is an object array (A) that stores the value of an object attribute in the A number into the B array.

var cars = [
var prices = cars.map(function(car){
    return car.price;
console.log(prices);//["CHEAP", "expensive"]

3. filter: Find out all elements from the array that meet the specified criteria

filter() detects numeric elements and returns an array of all elements that meet the criteria. filter() does not change the original array.

Scenario 1: Assuming there is an object array (A), get the object of the specified type in the array and put it in the B array.

var porducts = [
// es5
var filteredProducts = [];
for(var i = 0; i < porducts.length; i++){
    if(porducts[i].type === "fruit"){
console.log(filteredProducts);//[{name: "cucumber", type: "vegetable"},
                                 {name: "celery", type: "vegetable"}]
// es6 filter
var filtered2 = porducts.filter(function(product){
  return product.type === "vegetable";

Scenario 2: Suppose there is an array of objects (A) to filter out objects that do not satisfy the following conditions
Conditions: Vegetable quantity is more than 0, price is less than 10

var products = [
products = products.filter(function(product){
    return product.type === "vegetable" 
    && product.quantity > 0 
    && product.price < 10

Scenario 3: Assuming that there are two arrays (A,B), filter out the inconsistent data of B arrays according to the id value in A.

var post = {id:4,title:"Javascript"};
var comments = [
function commentsForPost(post,comments){
   return comments.filter(function(comment){
     return comment.postId === post.id;

find: Returns the value of the first element of the array passed the test (judged within the function)

Its parameter is a callback function, which is executed by all group members in turn until the first member whose return value is true is found and then returned to that member. If there are no qualified members, undefined is returned.
Use scenario 1
Assuming there is an array of objects (A), find eligible objects

 var users = [
// es5 method
 var user;
 for(var i = 0; i < users.length; i++){
  if(users[i].name === "Alex"){
    user = users[i];
    break;//Find it and terminate the loop
 console.log(user);// {name:"Alex",id:2}
// es6 find
user = users.find(function(user){
  return user.name === "Alex";
console.log(user);// {name:"Alex",id:2} finds and terminates the loop

Scenario 2: Assuming that there is an array of objects (A), find the eligible objects in the array according to the conditions of the specified objects.

var posts = [
var comment = {postId:1,content:"Hello World!"};
function postForComment(posts,comment){
 return posts.find(function(post){
   return post.id === comment.postId;
console.log(postForComment(posts,comment));//{id: 1, title: "React.js"}

5. Every&some

every: Whether each element in the array satisfies the specified condition

some: Are there elements in an array that satisfy specified conditions?

Scenario 1: Calculate whether each computer operating system in the object array is available or not, if it is more than 16 bits, the operating system is available or not.

//ES5 method
var computers = [
var everyComputersCanRunProgram = true;
var someComputersCanRunProgram = false;
for(var i = 0; i < computers.length; i++){
 var computer = computers[i];
 if(computer.ram < 16){
   everyComputersCanRunProgram = false;
   someComputersCanRunProgram = true;
//ES6 some every 
var every = computers.every(function(computer){
  return computer.ram > 16;
var some = computers.some(function(computer){
 return computer.ram > 16;

In a word: Every is true; Some is false.

Scenario 2: Assuming a registration page, determine whether all input content is longer than 0

function Field(value){
  this.value = value;
Field.prototype.validate = function(){
  return this.value.length > 0;
//ES5 method
var username = new Field("henrywu");
var telephone = new Field("18888888888");
var password = new Field("my_password");
//ES6 some every
var fields = [username,telephone,password];
var formIsValid = fields.every(function(field){
 return field.validate();
 // login was successful
  // Give users a friendly error warning

reduce: Combine numbers into a value

The reduce() method receives a method as an accumulator, and each value in the array (left to right) begins to merge and ends up with a value.

Scenario 1: Calculate the sum of all values in an array

 var numbers = [10,20,30];
 var sum = 0;
//es5 method
for(var i = 0; i < numbers.length; i++){
  sum += numbers[i];
// es6 reduce
var sumValue = numbers.reduce(function(sum2,number2){
  console.log(sum2);//0 10 30 60
  return sum2 + number2;
},0);//The initial value of sum2 is 0.

Use scenario 2:
Extracting an attribute of an object in an array into another array

 var primaryColors = [
 var colors = primaryColors.reduce(function(previous,primaryColor){
    return previous;
 console.log(colors);//["red", "yellow", "blue"]

Scenario 3: Determine whether parentheses are symmetrical in strings

function balancedParens(string){
  return !string.split("").reduce(function(previous,char){
    if(previous < 0) { return previous;}
    if(char == "("){ return ++previous;}
    if(char == ")"){ return --previous;}
    return previous;

Posted by golden_water on Sat, 19 Jan 2019 19:27:12 -0800