Sunday, March 26, 2023

React spread operator to operate on array

If you want to use the spread operator to add items to the beginning of an array, just use the spread operator after the new values. For example:


let a = [1, 2, 3, 4, 5];

let b = [0, ...a];


console.log(a);

console.log(b);

Additionally, you can also use .concat:


var a = [1, 2, 3, 4, 5];

var b = [0].concat(a);


console.log(a);

console.log(b);

references: 

https://stackoverflow.com/questions/42160400/react-redux-add-object-to-start-of-array-using-spread-operator

No comments:

Post a Comment