settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: First and Last K Numbers (JavaScript task)

+2 votes

Write a JavaScript function/code that prints the first k and the last k elements from an array of numbers.

The input comes as array of number elements:

  • The first element represents the number k
  • All other elements are from the array that needs to be processed.

Examples:

Input:
[2, 7, 8, 9]


Output:
7 8
8 9


Input:
[3, 6, 7, 8, 9]

Output:
6 7 8
7 8 9


The output is printed on the console on two lines:

  • On the first line print the first k elements, separated by space.
  • On the second line print the last k elements, separated by space.
asked in JavaScript category by user icabe

1 Answer

0 votes

First we need to take and remove the first element by using .shift operation:

function numbersK(arrNums) {
    let k = Number(arrNums.shift());//first we need to take and remove the first element!!! by using .shift operation (we need to get rid of it!)
    console.log(arrNums.slice(0,k).join(" "));
    console.log(arrNums.slice((arrNums.length-k),arrNums.length).join(" "));

}

numbersK([3,6,7,8,9]);

 

answered by user john7
...