Array#unshift mutates the array and returns the new length of the array.
For getting a new array, you could use Array#concat
return [static_stat].concat(api_data);
or take a new array with spreaded items.
return [static_stat, ...api_data];
Answer from Nina Scholz on Stack Overflowjavascript: unshift an object to an array of object - Stack Overflow
Basic JavaScript - Manipulate Arrays With unshift Method
The four common Javascript array methods Push, Pop, Shift and Unshift
Better performing alternative to Array.unshift
Videos
Array#unshift mutates the array and returns the new length of the array.
For getting a new array, you could use Array#concat
return [static_stat].concat(api_data);
or take a new array with spreaded items.
return [static_stat, ...api_data];
Yes, you are right. The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. But after using unshift() your original array api_data has been already updated. Just use a console.log(api_data) on it to see the updated array with new static_stat object like:
const static_stat = {id: null, name: 'UNASSIGNED'};
let api_data = [{id: 1, name: 'Jhon'}];
console.log(api_data.unshift(static_stat));
console.log(api_data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Javascript has a number of methods related to arrays which allow programmers to perform various array operations. There are four methods which are particularly used for adding and removing elements to and from an array. They are: push(), pop(), shift() and unshift(). For an experienced as well as new programmers, its likely to sometimes get confused how each of them work and which one to use in which situation. Thus, in this article, we have tried to simplify the concept with pictures and examples. Let's start exploring them one by one. Then we will compare their similarities and differences. Please look at the pictures too for better understanding.
https://foxbits.dev/article/four-common-javascript-array-methods-push-pop-shift-and-unshift/15
I was working on an small project and the reviewer suggest using an alternative to unshift since its a time-costly operation. I considered array.concat and spread operator but they seem to be slower than array.unshift?
simple snippet of what im doing, basically prepending an item to an array. This operation is taking place in a function that is going to be called very often.
const arr1 = [1,2,3,4,5,7,8,9]
const newArr1 = arr1.unshift("...")EDIT: This is just venting, not confusion on how the word is technically used by JS :D
OK, this is why I keep starting and stopping learning JS- reserved words with extremely unrelated English meanings. "Unshift" means a previous shift occurred. That's the only meaning for it in English. But JS decided to use it as a prepend array method. Argh!!
That is all...