1

I have a json array which I assign to a $scope object to display at the front-end. I want to rearrange this array on the basis of given id. This is how my initial array looks like.

$scope.listData = [{
id: 1,
name: adam,
title: testing title,
description: testing description
},
{
id: 2,
name: zampa,
title: testing title,
description: testing description
},
{
id: 3,
name: Aaron,
title: testing title,
description: testing description
}]

For rearrangement, For Instance if given id is 3, rearrangement of records should be like 3,1,2.

I have tried using angular.forEach loop, but did not succeed.

2
  • So you just want to move the item with the given ID to the start of the array? Commented Jul 8, 2019 at 6:24
  • correct. just rearrangement, no remove no deletion. Commented Jul 8, 2019 at 6:26

2 Answers 2

1

Here's a solution using splice() and unshift():

function moveToFront(id, array) {
  const i = array.findIndex(v => v.id === id);

  array.unshift(...array.splice(i, 1));
}

Complete snippet:

const listData = [{
    id: 1,
    name: 'adam',
    title: 'testing title',
    description: 'testing description'
  },
  {
    id: 2,
    name: 'zampa',
    title: 'testing title',
    description: 'testing description'
  },
  {
    id: 3,
    name: 'Aaron',
    title: 'testing title',
    description: 'testing description'
  }
];

function moveToFront(id, array) {
  const i = array.findIndex(v => v.id === id);
  
  array.unshift(...array.splice(i, 1));
}

moveToFront(3, listData);

console.log(listData);

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

3 Comments

unshift function just returning a number, not the array.
@ShaurBinTalib The function modifies the array in place (as per the question's requirements). There's no need to return anything.
yes I got it. Its working perfectly as per my requirement. Thankyou
0

//Assuming it is sorted by id initially, starting frm one

listData.splice(0, 0, listData.splice(id - 1, 1)[0]);

5 Comments

returns empty array
listData itself changed
This will only work once though. The second time the order of IDs will be different.
Yeah, that's the problem. However, I got my answer. Thankyou for your help.
ya correct, but then, idea of no deletion and only rearrangement is not there right, there is always new copy of array, anyway prob is solved

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.