12 Useful Array Tricks in JavaScript

12 Useful Array Tricks in JavaScript

Array is one of the most common concepts in Javascript. It provides us with many possibilities for processing data. It is necessary to be familiar with some common operations of array.

Array deduplication

1. from() superimposed on new Set() method

To remove duplicates from a string or numeric array, you can use the from method directly.

var plants = ['Saturn', 'Earth', 'Uranus', 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter'];
var uniquePlants = Array.from(new Set(plants)); 
console.log(uniquePlants); // [ 'Saturn', 'Earth', 'Uranus', 'Mercury', 'Venus', 'Mars', 'Jupiter' ]

2. Spread operator (…)

The spread operator is a major innovation of ES6 and has many powerful features.

var plants = ['Saturn', 'Earth', 'Uranus', 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter'];
var uniquePlants = [...new Set(plants)]; 
console.log(uniquePlants); // [ 'Saturn', 'Earth', 'Uranus', 'Mercury', 'Venus', 'Mars', 'Jupiter' ]

Replace specific values ​​in an array

The splice() method adds or removes items to or from an array and returns the removed items. This method mutates the original array. Pay special attention to where you insert the values!

// arrayObject.splice(index,howmany,item1,.....,itemX)

var plants = ['Saturn', 'Uranus', 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter'];
var result = plants.splice(2, 1, 'www.shanzhonglei.com')
console.log(plants); // ['Saturn','Uranus','www.shanzhonglei.com','Mercury','Venus','Earth','Mars','Jupiter']
console.log(result); // ['Mercury']

Mapping arrays without map()

Let's first introduce the map method. The map() method returns a new array. The elements in the array are the values ​​​​of the original array elements after calling the function. It will process the elements in the order of the original array elements. Note: map() does not mutate the original array and does not perform empty array detection.

Let's implement an array mapping without map:

// array.map(function(currentValue,index,arr), thisValue)

var plants = [
    { name: "Saturn" },
    { name: "Uranus" },
    { name: "Mercury" },
    { name: "Venus" },
]
var plantsName = Array.from(plants, ({ name }) => name);
console.log(plantsName); // [ 'Saturn', 'Uranus', 'Mercury', 'Venus' ]

Empty Array

If you want to clear an array, just set the length of the array to 0. Well, this is a bit simple.

var plants = ['Saturn', 'Earth', 'Uranus', 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter'];
plants.length = 0;
console.log(plants); // []

Convert an array to an object

If you want to convert an array to an object, the fastest way is to use the spread operator (...).

var plants = ['Saturn', 'Earth', 'Uranus', 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter'];
var plantsObj = { ... plants }
console.log(plantsObj); // {'0': 'Saturn','1': 'Earth', '2': 'Uranus','3': 'Mercury','4': 'Venus','5': 'Earth','6': 'Mars','7': 'Jupiter'}

Filling an array with data

If we need to fill the array with some data, or need a data with the same value, we can use the fill() method.

var plants = new Array(8).fill('8');
console.log(plants); // ['8', '8', '8', '8', '8', '8', '8', '8']

Merge Arrays

Of course you will think of the concat() method, but oh, the spread operator (...) is also very delicious, which is another application of the spread operator.

var plants1 = ['Saturn', 'Earth', 'Uranus', 'Mercury'];
var plants2 = ['Venus', 'Earth', 'Mars', 'Jupiter'];
console.log([...plants1, ...plants2]); // ['Saturn', 'Earth','Uranus', 'Mercury','Venus', 'Earth','Mars', 'Jupiter']

Intersection of two arrays

To find the intersection of two arrays, first make sure the arrays have no duplicates, then use the filter() method and the includes() method.

var plants1 = ['Saturn', 'Earth', 'Uranus', 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter'];
var plants2 = ['Saturn', 'Earth', 'Uranus'];
var alonePlants = [...new Set(plants1)].filter(item => plants2.includes(item));
console.log(alonePlants); // [ 'Saturn', 'Earth', 'Uranus' ]

Remove false values ​​from an array

We often need to remove false values ​​when processing data. In JavaScript, falsy values ​​are false, 0, " ", null, NaN, and undefined.

var plants = ['Saturn', 'Earth', null, undefined, false, "", NaN, 'Uranus', 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter'];
var trueArr = plants.filter(Boolean);
console.log(trueArr); // ['Saturn', 'Earth','Uranus', 'Mercury','Venus', 'Earth','Mars', 'Jupiter']

Get a random value from an array

We can get a random index number based on the array length.

var plants = ['Saturn', 'Earth', 'Uranus', 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter'];
console.log(plants[Math.floor(Math.random() * (plants.length + 1))])

lastIndexOf() Method

lastIndexOf() can help us find the index of the last occurrence of an element.

// array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

var nums = [1, 2, 3, 4, 5];
var sum = nums.reduce((x, y) => x + y);
console.log(sum); // 15

Add all the values ​​in an array

The reduce() method receives a function as an accumulator, and each value in the array (from left to right) is reduced to a single value.

// array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

var nums = [1, 2, 3, 4, 5];
var sum = nums.reduce((x, y) => x + y);
console.log(sum); // 15

This concludes this article about 12 useful array techniques in JavaScript. For more relevant JavaScript array content, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the new array methods in JavaScript es6
  • Detailed explanation of JS array methods
  • Detailed explanation of common methods of JavaScript arrays
  • Summary of several common methods of JavaScript arrays
  • Learn the common methods and techniques in JS arrays and become a master

<<:  Pure CSS to display the √ sign in the lower right corner after selecting the product

>>:  MySQL 8.0 WITH query details

Recommend

Vue uses rules to implement form field validation

There are many ways to write and validate form fi...

Example of Form action and onSubmit

First: action is an attribute of form. HTML5 has d...

JavaScript custom plug-in to implement tab switching function

This article shares the specific code of JavaScri...

JavaScript web page entry-level development detailed explanation

Part 3: ❤Three ways to overlook backend data rece...

MySQL Series 13 MySQL Replication

Table of contents 1. MySQL replication related co...

Detailed explanation of the use of the <meta> tag in HTML

In the web pages we make, if we want more people ...

JavaScript implements simple calculator function

This article example shares the specific code of ...

Tips to prevent others from saving as my web page and copying my site

Nowadays, copying websites is very common on the I...

HTML imitates Baidu Encyclopedia navigation drop-down menu function

HTML imitates the Baidu Encyclopedia navigation d...

React nested component construction order

Table of contents In the React official website, ...

Example of how to set automatic creation time and modification time in mysql

This article describes how to set the automatic c...

Detailed description of common events and methods of html text

Event Description onactivate: Fired when the objec...

JS uses map to integrate double arrays

Table of contents Preface Simulating data Merged ...

How to implement web stress testing through Apache Bench

1. Introduction to Apache Bench ApacheBench is a ...

How to turn local variables into global variables in JavaScript

First we need to know the self-calling of the fun...