reverse()
const originalArray = ['a', 'b', 'c'];
const reversedArray = originalArray.reverse();
console.log(reversedArray); // ['c', 'b', 'a']
reverse()
Проблема: Изменение оригинального массива
reverse()
const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reverse();
console.log(originalArray); // ['c', 'b', 'a']
console.log(newArray); // ['c', 'b', 'a']
Решение: Реверс элементов массива без изменения оригинальных данных
1. Использование slice
и reverse
slice()
reverse()
const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.slice().reverse();
console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // ['c', 'b', 'a']
2. Использование оператора spread
и reverse
spread
...
reverse()
const originalArray = ['a', 'b', 'c'];
const newArray = [...originalArray].reverse();
console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // ['c', 'b', 'a']
3. Использование reduce
и spread
reduce()
const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reduce((accumulator, value) => [value, ...accumulator], []);
console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // ['c', 'b', 'a']
4. Использование reduceRight
и spread
reduceRight()
reduce()
const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reduceRight((accumulator, value) => [...accumulator, value], []);
console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // ['c', 'b', 'a']
5. Использование push
и reduceRight
reduceRight()
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']