5 Array methods: IndexOf, filter, ForEach, map, reduce usages _javascript tips

Source: Internet
Author: User
Tags pear prev

The ECMASCRIPT5 standard, published on December 3, 2009, brings a number of new ways to improve the operations of existing array arrays. However, these novel array methods are not really popular because of the lack of browsers supporting ES5.

Array "Extras"

No one doubts the usefulness of these methods, but writing Polyfill (PS: Plug-ins compatible with older browsers) is not worthwhile for them. It turns "must-have" into "the best implementation". Some people actually refer to these array methods as an array "Extras". Hey!

But the times are changing. If you look at the popular open source JS project on GitHub, you will find that the trend is changing. Everyone wants to cut back on a lot of (third Third-party) dependencies, only in local code.

All right, 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'll pick 5 ways that I personally think are most useful and 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 IndexOf is not used

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);

After use

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

Console.log ("Found:", Arr.indexof ("Orange")!=-1);

2) Filter

The filter () method creates an array of new matching filter criteria.

Without filter ()

var arr = [
  {' name ': ' Apple ', ' Count ': 2},
  {' name ': ' Orange ', ' Count ': 5},
  {' name ': ' Pear ', ' count ': 3},< c17/>{"name": "Orange", "Count":},
];
  
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);


Using the filter ():

var arr = [
  {' name ': ' Apple ', ' Count ': 2},
  {' name ': ' Orange ', ' Count ': 5},
  {' name ': ' Pear ', ' count ': 3},
  { "Name": "Orange", "Count":},
];
  
var newArr = arr.filter (function (item) {return
  Item.name = = "Orange";
});


Console.log ("Filter results:", NEWARR);

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);
});

foreach is used to replace the For loop

4) Map ()

Map () After each element of the array is manipulated (mapped), a new array is returned,

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 ());

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 ());


Map () is a very useful function when processing the server to return data.

5) Reduce ()

Reduce () can implement an accumulator function that lowers each value of the array (left to right) to a value.

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

Scenario: Counting how many words in an array are not repeated

When you do not use reduce

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 ());

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 ());

Let me first explain my own understanding of reduce. Reduce (callback, InitialValue) passes in two variables. The callback function (callback) and the initial value (InitialValue). Suppose the function has an incoming argument, prev and Next,index, and array. Prev and next you have to understand.

Generally speaking, Prev starts with 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 Initivalvalue,next will be the first element in the array.

Like what:


* * The difference between the two, run in the console can know * * *

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 a additional parameter:", Passvalue ());

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.