MEMEPh. ideas that are worth sharing...

Elaborate on the commonly used methods of traversing arrays

Foreword


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

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

Let's look at another example: iterate over the values ​​in an array and calculate the sum

var numbers = [1,2,3,4,5];
var sum = 0;
numbers.forEach(number=>sum+=number)
console.log(sum)//15

 

2. map: map an array to another array


Map processes each element of the array through the specified function, and returns a new array after processing, 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 return is not given, it will return undefined by default.

 

Scenario 1

Suppose there is a numeric array (A), and the values ​​in the A array are doubled to the B array

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

 

Scenario 2

Suppose there is an object array (A), and store the value of an attribute of the object in the A number into the B array

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

 

Three, filter: find all elements from the array that meet the specified conditions


filter() detects numeric elements and returns an array of all elements that match the condition. filter() does not alter the original array.

 

Use scenario 1 :

Suppose there is an object array (A), get the objects of the specified type in the array and put them in the B array

var porducts = [
  {name:"cucumber",type:"vegetable"},
  {name:"banana",type:"fruit"},
  {name:"celery",type:"vegetable"},
  {name:"orange",type:"fruit"}
];

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

 

Use scenario 2 :

Suppose there is an object array (A), filter out the objects that do not meet the following conditions

Condition: The number of vegetables is greater than 0, and the price is less than 10

var products = [
  {name:"cucumber",type:"vegetable",quantity:0,price:1},
  {name:"banana",type:"fruit",quantity:10,price:16},
  {name:"celery",type:"vegetable",quantity:30,price:8},
  {name:"orange",type:"fruit",quantity:3,price:6}
];

products = products.filter(function(product){
    return product.type === "vegetable"
    && product.quantity > 0
    && product.price < 10
})
console.log(products);//[{name:"celery",type:"vegetable",quantity:30,price:8}]

 

Use scenario 3 :

Assuming that there are two arrays (A, B), according to the id value in A, filter out the data that does not match the B array

var post = {id:4,title:"Javascript"};
var comments = [
   {postId:4,content:"Angular4"},
   {postId:2,content:"Vue.js"},
   {postId:3,content:"Node.js"},
   {postId:4,content:"React.js"},
];

function commentsForPost(post,comments){
   return comments.filter(function(comment){
     return comment.postId === post.id;
   })
}
console.log(commentsForPost(post,comments));//[{postId:4,content:"Angular4"},{postId:4,content:"React.js"}]

 

Fourth, find: return the value of the first element of the array that passes the test (judgment within the function)


Its parameter is a callback function, and all array members execute the callback function in turn until the first member whose return value is true is found, and then the member is returned. Returns undefined if there are no eligible members.

 

Scenario 1

assumes that there is an array of objects (A), find the objects that meet the conditions

var users = [
  {name:"Jill"},
  {name:"Alex",id:2},
  {name:"Bill"},
  {name:"Alex"}
 ];
// es5 method
var user;
for(var i = 0; i < users.length; i++){
if(users[i].name === "Alex"){
user = users[i];
break; // terminate the loop when found
} 
}
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} will terminate the loop when it is found

 

Use scenario 2 :

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

var posts = [
{id:3,title:"Node.js"},
{id:1,title:"React.js"}
];
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"}

 

Five, every&some


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

some: Whether any element in the array meets the specified condition

 

Usage scenario 1 :

Calculate whether each computer operating system in the object array is available, if the operating system is greater than 16 bits, it is available, otherwise it is unavailable

//ES5 method
var computers = [
{name:"Apple",ram:16},
{name:"IBM",ram:4},
{name:"Acer",ram:32}
];
var everyComputersCanRunProgram = true;
var someComputersCanRunProgram = false;
for(var i = 0; i < computers.length; i++){
var computer = computers[i];
if(computer.ram < 16){
everyComputersCanRunProgram = false;
}else{
someComputersCanRunProgram = true;
} 
}
console.log(everyComputersCanRunProgram);//false
console.log(someComputersCanRunProgram);//true
//ES6 some every
var every = computers.every(function(computer){
return computer.ram > 16;
})
console.log(every);//false
var some = computers.some(function(computer){
return computer.ram > 16;
})
console.log(some);//true

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

 

Use scenario 2 :

Assuming there is a registration page, determine whether the length of all input content is greater 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");
console.log(username.validate());//true
console.log(telephone.validate());//true
console.log(password.validate());//true

//ES6 some every
var fields = [username,telephone,password];
var formIsValid = fields.every(function(field){
return field.validate();
})

console.log(formIsValid);//true
if(formIsValid){
 // registration success
}else{
// Give the user a friendly error reminder
}

 

6. reduce: combine an array into a value


The reduce() method receives a method as an accumulator, and each value in the array (from left to right) starts to be merged into a single value.

 

Usage 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];
}
console.log(sum);
// 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
console.log(sumValue);

 

Use scenario 2 :

Extract a property of an object in an array into another array

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

 

Use scenario 3 :

Determine whether the brackets in the string are symmetrical

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;
  },0);
}
console.log(balancedParens("((())))"));