HackerRank Solution in ES6 Javascript to Challenge: Arrays – DS

I just started to complete challenges over at HackerRank and this is the first challenge, Arrays – DS, under Data Structures > Arrays. I will be posting my solutions as I compete them. (Whenever I have time to actually work on them, haha)

[topads][/topads]

Arrays – DS

An array is a type of data structure that stores elements of the same type in a contiguous block of memory. In an array, A, of size N, each memory location has some unique index, i (where 0 <= i <= N), that can be referenced as A[i] (you may also see it written as Ai).

Input Format

The first line contains an integer, N (the number of integers in A).
The second line contains N space-separated integers describing A.

Constraints

  • 1 <= N <= 103
  • 1 <= Ai <= 104, where Ai is the ith integer in A

Output Format

Print all N integers in A in reverse order as a single line of space-separated integers.

Sample Input

4
1 4 3 2

Sample Output

2 3 4 1

My Solution to this Challenge

I submitted my answer using Javascript ES6, but below I give you three solutions, one in ES5 and two in ES6

ES5

var arr = [1, 2, 3, 4];
var string = "";
for (var i = arr.length - 1; i >= 0; i--) {
  string = string.concat(arr[i]) + " ";
}
console.log(string.trim());

Output

4 3 2 1

ES6

Using ‘forEach’ Helper

let arr = [1, 2, 3, 4];
let string = "";
arr.reverse().forEach((item) => (string = `${string} ${item}`));
console.log(string.trim());

Using ‘reduce’ Helper

let arr = [1, 2, 3, 4];
let string = "";
arr.reverse().reduce((prev, item) => (string = `${string} ${item}`), 0);
console.log(string.trim());

Output

4 3 2 1

Open in HackerRank

[bottomads][/bottomads]

Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.