patternjavascriptMinor
Copy part of array in javascript
Viewed 0 times
arraypartjavascriptcopy
Problem
I have an array and must fill another one.
Depending of a boolean I copy first or second element and the rest must be as is...
Currently I do it like this (
I've tried with shift and slice but no success...
¿how can I beautify this snippet?
Depending of a boolean I copy first or second element and the rest must be as is...
Currently I do it like this (
data has the desired info):const newArray = [];
newArray[0] = theBoolean ? data[0] : data[1];
for (let i = 2; i < data.length; i += 1) {
newArray[i - 1] = data[i];
}I've tried with shift and slice but no success...
¿how can I beautify this snippet?
Solution
You're on the right track trying
Initialisation
You could initialise
Pushing all other elements from data to newArray:
You could use
Using spread operator:
Using
Using
slice. Here's an example of using it with no loops required.Initialisation
You could initialise
newArray with an element directly in the declaration, removing the need for newArray[0] = ...:const newArray = [theBoolean ? data[0] : data[1]];Pushing all other elements from data to newArray:
You could use
Array.prototype.slice to get all other elements: data.slice(2).Using spread operator:
const newArray = [theBoolean ? data[0] : data[1]];
newArray.push(...data.slice(2));
// or, one liner:
const newArray = [theBoolean ? data[0] : data[1], ...data.slice(2)];Using
Array.prototype.concat:const newArray = [theBoolean ? data[0] : data[1]].concat(data.slice(2));Using
Function.prototype.apply:const newArray = [theBoolean ? data[0] : data[1]];
[].push.apply(newArray, data.slice(2));Code Snippets
const newArray = [theBoolean ? data[0] : data[1]];
newArray.push(...data.slice(2));
// or, one liner:
const newArray = [theBoolean ? data[0] : data[1], ...data.slice(2)];const newArray = [theBoolean ? data[0] : data[1]].concat(data.slice(2));const newArray = [theBoolean ? data[0] : data[1]];
[].push.apply(newArray, data.slice(2));Context
StackExchange Code Review Q#156432, answer score: 5
Revisions (0)
No revisions yet.