Search code examples
javascriptarraysobjectindexingfetch

How can you change the index of multiple array objects?


Problem:

How can you change the index of multiple objects within an array of 100 objects? In my case I would like to push them to the end of the array.

I have fetched a json array that contains over 100 objects, each with their own properties including a number property for each object that can be used to filter.

Attempts

  • I tried populating a variable using .splice to remove the specific array objects. Although .push wont accept that variable.
  • Also tried .slice but couldn't push the sliced objects to the end.
  • Also tried to loop through the original array using a for loop and an if statement with the condition of each objects "number" property.

Code: (the fetch is a success, only issue is the restructure of the array itself)

elementsArray.value = await data.json();

let removedElements = elementsArray.value.slice(56,71);

elementsArray.value.push(removedElements);

Solution

    1. With slice, the original array will not be modified. Use splice instead.

    2. push accepts one or more elements. so use spread syntax

    const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']
    
    const removedElements = animals.splice(2, 2)
    
    animals.push(...removedElements)
    
    // some other alternatives
    // Array.prototype.push.apply(animals, removedElements)
    // animals.concat(removedElements)
    
    console.log(animals)