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

Interpretation of 17 advertising effectiveness measures

1. 85% of ads go unread <br />Interpretatio...

Analysis of several situations where MySQL index fails

1. Best left prefix principle - If multiple colum...

Detailed example of using the distinct method in MySQL

A distinct Meaning: distinct is used to query the...

W3C Tutorial (15): W3C SMIL Activities

SMIL adds support for timing and media synchroniz...

What to do after installing Ubuntu 20.04 (beginner's guide)

Ubuntu 20.04 has been released, bringing many new...

Key knowledge summary of Vue development guide

Table of contents Overview 0. JavaScript and Web ...

Detailed analysis of MySQL optimization of like and = performance

introduction Most people who have used databases ...

CSS implements five common 2D transformations

2D transformations in CSS allow us to perform som...

Vue realizes cascading selection of provinces, cities and districts

Recently, I need to implement a cascading selecti...

Building FastDFS file system in Docker (multi-image tutorial)

Table of contents About FastDFS 1. Search for ima...

Example of using Docker to build an ELK log system

The following installations all use the ~/ direct...

Solution to the automatic stop of MySQL service

This article mainly introduces the solution to th...

Methods and steps to upgrade MySql5.x to MySql8.x

Several Differences Between MySQL 5.x and MySQL 8...

Vue sample code for online preview of office files

I'm working on electronic archives recently, ...