Home Web Front-end JS Tutorial 5 array Array methods: indexOf, filter, forEach, map, reduce usage examples_javascript skills

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

May 16, 2016 pm 04:17 PM
filter foreach indexof map reduce

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does springboot read lists, arrays, map collections and objects in yml files? How does springboot read lists, arrays, map collections and objects in yml files? May 11, 2023 am 10:46 AM

application.yml defines the list collection. The first way is to use the @ConfigurationProperties annotation to obtain all the values ​​​​of the list collection type:code:status:-200-300-400-500. Write the entity class corresponding to the configuration file. What needs to be noted here is that defining the list Collection, first define a configuration class Bean, and then use the annotation @ConfigurationProperties annotation to obtain the list collection value. Here we will explain the role of the relevant annotations. @Component hands over the entity class to Spring management @ConfigurationPropertie

What is the difference between using foreach and iterator to delete elements when traversing Java ArrayList? What is the difference between using foreach and iterator to delete elements when traversing Java ArrayList? Apr 27, 2023 pm 03:40 PM

1. The difference between Iterator and foreach is the polymorphic difference (the bottom layer of foreach is Iterator) Iterator is an interface type, it does not care about the type of collection or array; both for and foreach need to know the type of collection first, even the type of elements in the collection; 1. Why is it said that the bottom layer of foreach is the code written by Iterator: Decompiled code: 2. The difference between remove in foreach and iterator. First, look at the Alibaba Java Development Manual, but no error will be reported in case 1, and an error will be reported in case 2 (java. util.ConcurrentModificationException) first

How to determine the number of foreach loop in php How to determine the number of foreach loop in php Jul 10, 2023 pm 02:18 PM

​The steps for PHP to determine the number of the foreach loop: 1. Create an array of "$fruits"; 2. Create a counter variable "$counter" with an initial value of 0; 3. Use "foreach" to loop through the array, and Increase the value of the counter variable in the loop body, and then output each element and their index; 4. Output the value of the counter variable outside the "foreach" loop to confirm which element the loop reaches.

How to set expiration time map in Java How to set expiration time map in Java May 04, 2023 am 10:13 AM

1. Technical background In actual project development, we often use caching middleware (such as redis, MemCache, etc.) to help us improve the availability and robustness of the system. But in many cases, if the project is relatively simple, there is no need to specifically introduce middleware such as Redis to increase the complexity of the system in order to use caching. So does Java itself have any useful lightweight caching components? The answer is of course yes, and there is more than one way. Common solutions include: ExpiringMap, LoadingCache and HashMap-based packaging. 2. Technical effects to realize common functions of cache, such as outdated deletion strategy, hotspot data warm-up 3. ExpiringMap3.

What are the ways to implement thread safety for Map in Java? What are the ways to implement thread safety for Map in Java? Apr 19, 2023 pm 07:52 PM

Method 1. Use HashtableMapashtable=newHashtable(); This is the first thing everyone thinks of, so why is it thread-safe? Then take a look at its source code. We can see that our commonly used methods such as put, get, and containsKey are all synchronous, so it is thread-safe publicsynchronizedbooleancontainsKey(Objectkey){Entrytab[]=table;inthash=key.hashCode( );intindex=(hash&0x7FFFFFFF)%tab.leng

How to convert objects to Maps in Java - using BeanMap How to convert objects to Maps in Java - using BeanMap May 08, 2023 pm 03:49 PM

There are many ways to convert javabeans and maps, such as: 1. Convert beans to json through ObjectMapper, and then convert json to map. However, this method is complicated and inefficient. After testing, 10,000 beans were converted in a loop. , it takes 12 seconds! ! ! Not recommended. 2. Obtain the attributes and values ​​of the bean class through Java reflection, and then convert them into the key-value pairs corresponding to the map. This method is the second best, but it is a little more troublesome. 3. Through net.sf.cglib.beans.BeanMap Method in the class, this method is extremely efficient. The difference between it and the second method is that because of the use of cache, the bean needs to be initialized when it is first created.

How to configure and use the map module in Nginx server How to configure and use the map module in Nginx server May 21, 2023 pm 05:14 PM

The map directive uses the ngx_http_map_module module. By default, nginx loads this module unless artificially --without-http_map_module. The ngx_http_map_module module can create variables whose values ​​are associated with the values ​​of other variables. Allows classification or simultaneous mapping of multiple values ​​​​to multiple different values ​​​​and storage in a variable. The map directive is used to create a variable, but only performs the view mapping operation when the variable is accepted. For processing requests that do not reference variables, this The module has no performance shortcomings. 1.ngx_http_map_module module instruction description map syntax

Optimize the performance of Go language map Optimize the performance of Go language map Mar 23, 2024 pm 12:06 PM

Optimizing the performance of Go language map In Go language, map is a very commonly used data structure, used to store a collection of key-value pairs. However, map performance may suffer when processing large amounts of data. In order to improve the performance of map, we can take some optimization measures to reduce the time complexity of map operations, thereby improving the execution efficiency of the program. 1. Pre-allocate map capacity. When creating a map, we can reduce the number of map expansions and improve program performance by pre-allocating capacity. Generally, we

See all articles