Trying a new segment called #CodeRecipes. I want to cover questions that I often google. These are recipes that you should definitely keep handy because it’s not a matter “if” you use it, but “when” 😉
const benjamin = ['👶','👦', '👨', '👴'];
const benjaminButton = benjamin.reverse();
console.log(benjaminButton);
// ['👴', '👨', '👦', '👶']
One thing to note is that it mutates the original array.
const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reverse();
console.log(originalArray); // [ 'c', 'b', 'a' ]
console.log(newArray); // [ 'c', 'b', 'a' ]
Here are some recipes that won’t mutate the original array. Let’s take a look 👀
slice
and reverse
const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.slice().reverse();
console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]
spread
and reverse
const originalArray = ['a', 'b', 'c'];
const newArray = [...originalArray].reverse();
console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]
reduce
and spread
const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reduce((accumulator, value) => {
return [value, ...accumulator]
}, []);
console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]
reduceRight
and spread
const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reduceRight((accumulator, value) => {
console.log(value);
return [...accumulator, value]
}, []);
console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]
Or using push
const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reduceRight((accumulator, value) => {
accumulator.push(value);
return accumulator;
}, []);
console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]
Source code and tests are available here
#javascript #arrays