TZinovieva

First and Last K Numbers JS Fundamentals

Feb 6th, 2023
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. firstAndLastKNumbers([2, 7, 8, 9]);
  2.  
  3. function firstAndLastKNumbers(arr) {
  4.     let k = arr.shift(); // (3) [7, 8, 9]
  5.     // k = 2 - the removed element from the original array
  6.  
  7.     let firstLine = arr.slice(0, k) // (2) [7, 8];
  8.     // k shows the count of numbers per line
  9.  
  10.     let secondLine = arr.slice(arr.length - k, arr.length); // (2) [8, 9]
  11.     // arr.length - k = 3 - 2 = 1 -- the start index of slice function which is 8
  12.  
  13.     console.log(firstLine.join(' '));
  14.     console.log(secondLine.join(' '));
  15. }
Advertisement
Add Comment
Please, Sign In to add comment