Reputation: 601
I would like to find out if swapping elements can be done using only .reduce
in JavaScript. If not, what else should be used from the functional programming land?
This is not for sorting an array. I wanted to find all the permutations of the array element using .reduce
which required the swap step as per this method.
Upvotes: 1
Views: 2926
Reputation: 2484
In es6, the idiomatic way to swap array elements is:
;[a[i], a[j]] = [a[j], a[i]]
Using .reduce
is not appropriate for this task. You could technically do something like this:
a = a.reduce((acc, element, idx) => {
acc.push(idx === i ? a[j] : idx === j ? a[i] : a[idx])
return acc
}, [])
but it would result in convoluted code.
If your goal is to avoid mutating the original array, you can use Object.assign
:
b = Object.assign([], a, {[i]: a[j], [j]: a[i]})
Upvotes: 4
Reputation: 959
The reduce
function reduces the array to a value of an object, as defined by the accumulator
.
let array1 = [2, 5, 8, 0, 10];
let array2 = [1, 4, 9, 7, 6];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
The sort()
method sorts the elements of an array in place and returns the array. The default sort order is built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
var months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]
const sortingAccending = (a, b) => a - b
let numbers = [4, 2, 5, 1, 3];
numbers.sort(sortingAccending);
console.log(numbers);
// expected output: Array [1, 100000, 21, 30, 4]
And you answer your question, reduce
can't be used for swapping elements.
You will have to either use sort
for write your custom sort function
Upvotes: 0
Reputation: 386680
You could take a function which takes an array and two indices and uses a destructuring assignment.
const swap = (array, i, j) => [array[i], array[j]] = [array[j], array[i]];
var array = [1, 2, 3];
swap(array, 0, 1)
console.log(array);
A version with reduce by taking an array of indices and swap all pairs from start to end.
const
swap = (array, ...indices) =>
indices.reduce((a, b) => ([array[a], array[b]] = [array[b], array[a]], b));
var array = [1, 2, 3];
swap(array, 0, 1)
console.log(array);
Upvotes: 4