Reputation: 345
var reverse = function (list) {
return list.reduce(function (reversedList, current) {
return [ current ].concat(reversedList);
}, []);
};
console.log(reverse([1,2,3,4]));
So this is for reversing an array in Javascript using reduce. According to MDNs ref. The second argument(here current) is the second element after the first element of the array if no initialValue is provided. But in this case, the current is not the second element but the last element of the array. Why is it so?
You can run this code on the console for some array [1,2,3,4] and current will be returning 4.
Upvotes: 1
Views: 2565
Reputation: 2733
What your code is doing is creating a new array with the current item in it when you do this: [current] and then concatenating the "reversedList" array after it.
var reverse = function (list) {
return list.reduce(function (reversedList, current) {
//this creates a new array with just the "current" item in it
//and then concatenates the "reversedList" array with it.
console.log("concatenating ", current, "with", reversedList);
return [ current ].concat(reversedList);
}, []);
};
console.log(reverse([1,2,3,4]));
This is kind of a weird way to go about doing that but I assume it is just for educational purposed. You could just add each item to the beginning of the array rather than concatenating.
var reverse = function (list) {
return list.reduce(function (reversedList, current) {
reversedList.unshift(current);
return reversedList;
}, []);
};
console.log(reverse([1,2,3,4]));
That said, if you are just trying to reverse an array you can use the reverse() method:
console.log([1,2,3,4].reverse());
Upvotes: 3