Adi
Adi

Reputation: 57

Print array of numbers in Javascript in this order (first-last, second-last second....)

Write a "PrintZigZag" program that provides an array of 10 integers containing any values and prints the elements in the following order: the first-the last, the second-the last second, etc ... (The program must be written pretending not to know what the values entered in the array are)

This was a interview question for a position of "Junior Web Developer" and i didn't know how to solve it...

let numbers = [1,2,3,4,5,6,7,8,9,10];

Upvotes: 1

Views: 1420

Answers (2)

Cameron
Cameron

Reputation: 607

Here's Sweet Chilly Philly's solution using .map. An interviewer will probably want to see you use the for loop, but knowing modern loops could help as well.

let arr = [];
numbers.map(item => {
   arr.push(item);
   arr.push(numbers[numbers.length - 1])
   numbers.pop()
})

And here's a solution with a do, while loop as Peter S mentioned. Be careful with these since they can end in an infinite loop if not escaped correctly.

let arr = [];
do {
  arr.push(numbers[0])
  arr.push(numbers[numbers.length - 1])
  numbers.shift()
  numbers.pop()
} while (numbers.length > 0)

Upvotes: 0

Sweet Chilly Philly
Sweet Chilly Philly

Reputation: 3219

this is the result you're looking for?

[1, 10, 2, 9, 3, 8, 4, 7, 5, 6]

I really enjoy interview questions, thankyou for sharing. please let me help explain what im doing here

let numbers = [1,2,3,4,5,6,7,8,9,10];
var result = [];
for(i=1; i< numbers.length+1 /2; i++) {
    result.push(i);
    result.push(numbers.pop());

}

I am looping over half the array starting at 1. Then I am pushing the first index onto the result array, and then straight after I am popping off the last number of the array.

This will build up a new array consisting of the first number and then the last number, eventually reaching the end.

Upvotes: 2

Related Questions