habs
habs

Reputation: 89

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

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);

Upvotes: 2

Views: 1331

Answers (2)

Aalexander
Aalexander

Reputation: 5004

Here is a way you can use splice to append a to b but as in the commentarys mentioned for this use case .concat() or .push(...otherArray) is the better choice

let a = [1,2,3],
    b = [4,5,6];
    a.splice(0, 0, ...b);
    
    console.log(a);

Upvotes: 1

User863
User863

Reputation: 20039

  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)

Upvotes: 2

Related Questions