将两个数组合并为一个 - Javascript

Join two arrays in to one - Javascript

我正在尝试将数组合并为一个。

var newArray = ['11:30', '12:00','12:30', '13:00' ,'13:30', '14:00'];
result = ["10:00","16:00"];   // this is coming from my db

当我尝试合并它们时,我得到 7 不知道为什么

var nameArr = timeBeenSelected.toString();
console.log(nameArr);
var nameArr2 = timeBeenSelected.split(',');
console.log(nameArr2);
console.log(newArray.push(result));

console.log(结果); ["10:00","16:00"]

console.log(newArray); (6) [“11:30”、“12:00”、“12:30”、“13:00”、“13:30”、“14:00”]

使用concat instead of push将数组相互组合。

var nameArr = timeBeenSelected.toString();
console.log(nameArr);
var nameArr2 = timeBeenSelected.split(',');
console.log(nameArr2);
console.log(nameArr2.concat(result));

这是解决方案

var newArray = ['11:30', '12:00','12:30', '13:00' ,'13:30', '14:00'];
var result = ["10:00","16:00"]// Make sure whatever the data you are getting it should be JSON
//If it is in string just convert your result like as follows
//result=JSON.parse(result)

var finalResult = [...new Set([...newArray,...result])].sort()
console.log(finalResult)

代码说明

[...newArray,...result]//This will return joined array

上面的数组可以是重复的结果所以我使用 new Set() 来获取唯一值。

[...new Set([...newArray,...result])]

现在终于使用可选的 sort() function 对值进行排序

使用 ES6,您可以通过

连接 2 个数组
let newArray = ['11:30', '12:00','12:30', '13:00' ,'13:30', '14:00'];
let result = ["10:00","16:00"]
let combined = [..newArray,..result];

您可以使用 spread operator 合并两个数组,检查下面的代码片段

var newArray = ['11:30', '12:00','12:30', '13:00' ,'13:30', '14:00'];
var result = ["10:00","16:00"]

var output = [...newArray, ...result] //without mutating the input arrays 

console.log(output) // total 8 elements

array1 = ['a', 'b'];
array2 = ['c', 'd'];

经典 js:只需连接两个数组。

array1.concat(array2)

es6: 你可以看一眼析构 示例:

unifyArr = [...array1, ...array2]