skip to Main Content

I am learning JS and have a task to complete which is quite confusing. The task is to giving a index to start from and include the remainders or the the items missing in the array, as well as to display them in angular. This is what i have

const arr = ["a", "b" ,"c" ,"d"]

const startIndex = 2:

let arr2 = arr.slice(startIndex, arr.length)

Output

["c","d"]

// a and b are ignore and don't see a way to display them accordingly

The tasks is to start let’s say at index 2 through the last item and include items a and b which are the items missing when using slice method

2

Answers


  1. Heres an example with your code above:

    JS

    const arr = ["a", "b", "c", "d"];
    const startIndex = 2;
    let arr2 = [...arr.slice(startIndex), ...arr.slice(0, startIndex)];
    console.log(arr2);
    

    The is the spread operator, it allows an iterable (like an array expression) to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.

    Angular Example:

    <div *ngFor="let item of arr2">{{item}}</div>
    
    Login or Signup to reply.
  2. You could use the original array copied twice:

    const arr = ["a", "b", "c", "d"]
    const startIndex = 2;
    
    const result = [...arr, ...arr]
      .slice(startIndex, startIndex + arr.length);
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search