Nick
Nick

Reputation: 2980

Fast way to push and shift arrays in ES6

I have a data stream which continuously needs to update an array. The array itself is always bigger than the stream which is coming in. This would mean that I have to concat the buffer to the array and shift everything. However, concatenation is slow so I was wondering if there is a fast way of doing this?

Example:

var array = [1,2,3,4,5,6];
var stream = [7,8,9];
array = magicalFunction(array,stream); // outputs [4,5,6,7,8,9]

The array function is used for plotting with ChartJS. It's a rolling plot so as data comes in (it comes in chunks) I have to update the chart by shifting the entire data set.

Upvotes: 2

Views: 15377

Answers (5)

ASHISH R
ASHISH R

Reputation: 4189

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])

Upvotes: 0

Behnam Azimi
Behnam Azimi

Reputation: 2488

Maybe it's late to answer but you could do this with ES6 like this:

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))

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386568

You could use spread syntax .... But if that is faster than 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);

With Array.concat

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);

With Array.unshift

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);

Upvotes: 8

NullDev
NullDev

Reputation: 7303

How about a Spread

var stream = [7,8,9];
var array = [1,2,3,4,5,6, ...stream];

Upvotes: 0

Stuart
Stuart

Reputation: 6795

You can apply a .push:

array.push.apply(array, stream);

or in ES2015 you can use the triple dots:

array.push(...stream)

Upvotes: 1

Related Questions