我有一个不断需要更新数组的数据流。数组本身总是比正在进入的流大。这意味着我必须将缓冲区连接到数组并移动所有内容。但是,连接速度很慢所以我想知道是否有一种快速的方法可以做到这一点?
示例:
var array = [1,2,3,4,5,6];
var stream = [7,8,9];
array = magicalFunction(array,stream); // outputs [4,5,6,7,8,9]
数组函数用于使用ChartJS进行绘图。这是一个滚动的情节,因为数据进入(它以块为单位)我必须通过移动整个数据集来更新图表。
答案 0 :(得分:7)
您可以使用spread syntax ...
。但如果这比concat快......?
var magicalFunction = (a, s) => [...a.slice(s.length - a.length), ...s],
array = [1, 2, 3, 4, 5, 6],
stream = [7, 8, 9];
array = magicalFunction(array,stream);
console.log(array);

var magicalFunction = (a, s) => a.slice(s.length - a.length).concat(s);
array = [1, 2, 3, 4, 5, 6],
stream = [7, 8, 9];
array = magicalFunction(array,stream);
console.log(array);

var magicalFunction = (a, s) => (s.unshift(...a.slice(s.length - a.length)), s);
array = [1, 2, 3, 4, 5, 6],
stream = [7, 8, 9];
array = magicalFunction(array,stream);
console.log(array);

答案 1 :(得分:0)
您可以申请.push:
array.push.apply(array, stream);
或在ES2015中,您可以使用三点:
array.push(...stream)
答案 2 :(得分:0)
传播怎么样
var stream = [7,8,9];
var array = [1,2,3,4,5,6, ...stream];
答案 3 :(得分:0)
也许答案来晚了,但是您可以使用ES6来做到这一点:
let array = [1, 2, 3, 4, 5, 6];
let stream = [7, 8, 9, 1];
const mergedArray = [...array, ...stream]
// fetch only distinct values
const distinctMergedArray = Array.from(new Set(mergedArray))
答案 4 :(得分:0)
let array = [1, 2, 3, 4, 5, 6];
let stream = [7, 8, 9, 1];
//set to get distinct value and spread operator to merge two arrays
const resultArray = new Set([...array, ...stream])