Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
I am looking for a way to get my array to create a new array, with numbers in reverse without using the reverse method.
e.g.
let numbers = [1, 2, 3] console.log(reverse(numbers))
should return “[3, 2, 1]”.
“[3, 2, 1]”
Thanks
const numbers = [1, 2, 3, 4, 5, 6]; const result = numbers.reduce((a, b) => [b].concat(a), []);
Here. A quick solution with map. returns you new array
let numbers = [1, 2, 3] let result = numbers.map((el, i, arr) => arr[arr.length - 1 - i]) console.log(result)
Add a comment
Here is a quick way using a standard for loop
const numbers = [1, 2, 3] const reverse = []; for (let i = numbers.length - 1; i >= 0; i--) { reverse.push(numbers[i]) } console.log(reverse);
Short and simple:
let numbers = [1, 2, 3, 4]; const reverse = (array) => array.map(array.pop, [...array]); console.log(reverse(numbers));
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.
const numbers = [1, 2, 3, 4, 5, 6]; const result = numbers.reduce((a, b) => [b].concat(a), []);