1

I have an array of objects, each with an 'id' and a 'name'. I'm retrieving an 'id' from the server and need to reorder the array starting from this id.

Example code:

var myList = [
  {
    id: 0,
    name: 'Joe'
  },
  {
    id: 1,
    name: 'Sally'
  },
  {
    id: 2,
    name: 'Chris'
  },
  {
    id: 3,
    name: 'Tiffany'
  },
  {
    id: 4,
    name: 'Kerry'
  }
];

Given an 'id' of 2, how can I reorder the array so my output is as follows:

var newList = [
  {
    id: 2,
    name: 'Chris'
  },
  {
    id: 3,
    name: 'Tiffany'
  },
  {
    id: 4,
    name: 'Kerry'
  },
  {
    id: 0,
    name: 'Joe'
  },
  {
    id: 1,
    name: 'Sally'
  }
];

5 Answers 5

1

Try this:

function orderList(list, id){
  return list.slice(id).concat(list.slice(0,id));
}

Link to demo

Sign up to request clarification or add additional context in comments.

1 Comment

Some assumptions in my data lend this solution to be the, seemingly, simplest solution. Other solutions provided also worked!
1

You could slice the array at given index and return a new array using spread syntax.

const myList = [{id:0,name:'Joe'},{id:1,name:'Sally'},{id:2,name:'Chris'},{id:3,name:'Tiffany'},{id:4,name:'Kerry'}];

const slice = (arr, num) => [...arr.slice(num), ...arr.slice(0, num)];

console.log(slice(myList, 2));

1 Comment

For a common case where ids can be not incremental you can also define num using findIndex for example, so that num and id are decoupled from each other.
0
myList.sort(function(a,b){
 return a.id>2===b.id>2?a.id-b.id:b.id-a.id;
});

newList=myList;

http://jsbin.com/kenobunali/edit?console

1 Comment

You are allowed to use spaces :P
0

You could splice the wanted part and use splice to insert it at the end of the array.

var myList = [{ id: 0, name: 'Joe' }, { id: 1, name: 'Sally' }, { id: 2, name: 'Chris' }, { id: 3, name: 'Tiffany' }, { id: 4, name: 'Kerry' }],
    id = 2;
    
myList.splice(myList.length, 0, myList.splice(0, myList.findIndex(o => o.id === id)));

console.log(myList);

Comments

0

using es6 spread syntax

var myList = [{ id: 0, name: 'Joe' }, { id: 1, name: 'Sally' }, { id: 2, name: 'Chris' }, { id: 3, name: 'Tiffany' }, { id: 4, name: 'Kerry' }],
id = 2;
var index = myList.findIndex(o => o.id == id);
var arr = myList.splice(0, index);
var result = [...myList, ...arr];
console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.