Merge two arrays in JS

There are many ways to merge two arrays in JavaScript, the following are some of the common ones:

  1. concat() method

The concat() method concatenates two or more arrays and returns a new array. This method does not alter the original array.

Sample code:

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let newArr = arr1.concat(arr2);
console.log(newArr); // [1, 2, 3, 4, 5, 6]
  1. spread operator

Using ES6's new spread operator can combine two arrays more easily.

Sample code:

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let newArr = [...arr1, ...arr2];
console.log(newArr); // [1, 2, 3, 4, 5, 6]
  1. push() method

One array can be added to the end of another array using the push() method.

Sample code:

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
arr1.push(...arr2);
console.log(arr1); // [1, 2, 3, 4, 5, 6]

No matter which method is used in the above three methods, the original array will not be changed, but a new array will be returned.

  1. splice() method

The splice() method can add or delete elements at a specified position, and can also be used to merge two arrays.

Sample code:

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
Array.prototype.splice.apply(arr1, [arr1.length, 0].concat(arr2));
console.log(arr1); // [1, 2, 3, 4, 5, 6]
  1. reduce() method

The reduce() method can traverse the array and return a cumulative value, and achieve the effect of merging two arrays through accumulation.

Sample code:

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let newArr = arr2.reduce(function(result, item) {
  result.push(item);
  return result;
}, arr1);
console.log(newArr); // [1, 2, 3, 4, 5, 6]

These are common methods, and developers can choose different methods according to specific needs.

Guess you like

Origin blog.csdn.net/weixin_53156345/article/details/131005248