Home > Web Front-end > JS Tutorial > body text

5 array Array methods: indexOf, filter, forEach, map, reduce usage examples_javascript skills

WBOY
Release: 2016-05-16 16:17:20
Original
1404 people have browsed it

The ECMAScript5 standard was released on December 3, 2009. It brings some new methods to improve existing Array array operations. However, these newfangled array methods never really caught on because there was a lack of ES5-enabled browsers on the market at the time.

Array "Extras"

No one doubts the practicality of these methods, but writing polyfills (PS: plug-ins compatible with older browsers) is not worth it for them. It turns "must be achieved" into "best achieved". Some people actually call these array methods Array "Extras". Why!

But times are changing. If you look at popular open source JS projects on Github, you'll see that the tide is turning. Everyone wants to cut down a lot of dependencies (on third-party libraries) and only use local code to achieve it.

Okay, let’s get started.

My 5 arrays

In ES5, there are a total of 9 Array methods http://kangax.github.io/compat-table/es5/

Note* Nine methods

Array.prototype.indexOf
Array.prototype.lastIndexOf
Array.prototype.every
Array.prototype.some
Array.prototype.forEach
Array.prototype.map
Array.prototype.filter
Array.prototype.reduce
Array.prototype.reduceRight

I will pick 5 methods that I personally think are the most useful and that many developers will encounter.

1) indexOf

The indexOf() method returns the position of the first element found in the array, or -1 if it does not exist.

When not using indexOf

var arr = ['apple','orange','pear'],
found = false;

for(var i= 0, l = arr.length; i< l; i++){
if(arr[i] === 'orange'){
found = true;
}
}

console.log("found:",found);

Copy after login

After use

var arr = ['apple','orange','pear'];

console.log("found:", arr.indexOf("orange") != -1);

Copy after login

2) filter

The filter() method creates a new array matching the filter conditions.

When filter() is not used

var arr = [
  {"name":"apple", "count": 2},
  {"name":"orange", "count": 5},
  {"name":"pear", "count": 3},
  {"name":"orange", "count": 16},
];
  
var newArr = [];

for(var i= 0, l = arr.length; i< l; i++){
  if(arr[i].name === "orange" ){
newArr.push(arr[i]);
}
}

console.log("Filter results:",newArr);

Copy after login


Used filter():

var arr = [
  {"name":"apple", "count": 2},
  {"name":"orange", "count": 5},
  {"name":"pear", "count": 3},
  {"name":"orange", "count": 16},
];
  
var newArr = arr.filter(function(item){
  return item.name === "orange";
});


console.log("Filter results:",newArr);

Copy after login

3) forEach()

forEach executes the corresponding method for each element

var arr = [1,2,3,4,5,6,7,8];

// Uses the usual "for" loop to iterate
for(var i= 0, l = arr.length; i< l; i++){
console.log(arr[i]);
}

console.log("========================");

//Uses forEach to iterate
arr.forEach(function(item,index){
console.log(item);
});

Copy after login

forEach is used to replace the for loop

4) map()

After map() performs certain operations (mapping) on ​​each element of the array, it will return a new array,

Do not use map

var oldArr = [{first_name:"Colin",last_name:"Toh"},{first_name:"Addy",last_name:"Osmani"},{first_name:"Yehuda",last_name:"Katz"}];

function getNewArr(){
  
  var newArr = [];
  
  for(var i= 0, l = oldArr.length; i< l; i++){
    var item = oldArr[i];
    item.full_name = [item.first_name,item.last_name].join(" ");
    newArr[i] = item;
  }
  
  return newArr;
}

console.log(getNewArr());

Copy after login

After using map

var oldArr = [{first_name:"Colin",last_name:"Toh"},{first_name:"Addy",last_name:"Osmani"},{first_name:"Yehuda",last_name:"Katz"}];

function getNewArr(){
    
  return oldArr.map(function(item,index){
    item.full_name = [item.first_name,item.last_name].join(" ");
    return item;
  });
  
}

console.log(getNewArr());

Copy after login


map() is a very practical function when processing data returned by the server.

5) reduce()

reduce() can implement the function of an accumulator, reducing each value of the array (from left to right) to a value.

To be honest, it was a little difficult to understand this sentence at first because it is too abstract.

Scenario: Count how many unique words there are in an array

When reduce is not used

var arr = ["apple","orange","apple","orange","pear","orange"];

function getWordCnt(){
  var obj = {};
  
  for(var i= 0, l = arr.length; i< l; i++){
    var item = arr[i];
    obj[item] = (obj[item] +1 ) || 1;
  }
  
  return obj;
}

console.log(getWordCnt());

Copy after login

After using reduce()

var arr = ["apple","orange","apple","orange","pear","orange"];

function getWordCnt(){
  return arr.reduce(function(prev,next){
    prev[next] = (prev[next] + 1) || 1;
    return prev;
  },{});
}

console.log(getWordCnt());

Copy after login

Let me first explain my own understanding of reduce. reduce(callback, initialValue) will pass in two variables. Callback function (callback) and initial value (initialValue). Assume that the function has incoming parameters, prev and next, index and array. You must understand prev and next.

Generally speaking, prev starts from the first element in the array, and next is the second element. But when you pass in the initial value (initialValue), the first prev will be the initialValue, and next will be the first element in the array.

For example:

/*
* 二者的区别,在console中运行一下即可知晓
*/

var arr = ["apple","orange"];

function noPassValue(){
  return arr.reduce(function(prev,next){
    console.log("prev:",prev);
    console.log("next:",next);
    
    return prev + " " +next;
  });
}
function passValue(){
  return arr.reduce(function(prev,next){
    console.log("prev:",prev);
    console.log("next:",next);
    
    prev[next] = 1;
    return prev;
  },{});
}

console.log("No Additional parameter:",noPassValue());
console.log("----------------");
console.log("With {} as an additional parameter:",passValue());

Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!