Home > Back-end >  How to move duplicate to first index in an array of Objects?
How to move duplicate to first index in an array of Objects?

Time:07-16

I have below variable with array of Objects

let Obj1 =

    [
    {Id: 123, name: 'A'},
    {Id: 124, name: 'B'},
    {Id: 125, name: 'C'},
    {Id: 126, name: 'D'},
    {Id: 127, name: 'E'}
    ]

let Obj2 = {Id:126, name: 'D'}

How do I move the Obj2 in Obj1 to the 0th index dynamically in Javascript or TypeScript? Obj2 is from backend and Obj1 is the data already present in frontend The End result should be as below

[
{Id: 126, name: 'D'},
{Id: 123, name: 'A'},
{Id: 124, name: 'B'},
{Id: 125, name: 'C'},
{Id: 127, name: 'E'}
]

CodePudding user response:

let Obj1 =
    [
    {id: 123, name: 'A'},
    {id: 124, name: 'B'},
    {id: 125, name: 'C'},
    {id: 126, name: 'D'},
    {id: 127, name: 'E'}
    ];

let Obj2 = {id:126, name: 'D'};

let new_array = Obj1.reduce((curr, acc)=>(acc.id === Obj2.id ? curr.unshift(acc) : curr.push(acc), curr), []);

console.log(new_array);

CodePudding user response:

let Obj1 =

    [
        {Id: 123, name: 'A'},
        {Id: 124, name: 'B'},
        {Id: 125, name: 'C'},
        {Id: 126, name: 'D'},
        {Id: 127, name: 'E'}
    ]

let Obj2 = {Id:126, name: 'D'}

for (let i = 0; i < Obj1.length; i  ) {
    if (Obj1[i].Id === Obj2.Id && Obj1[i].name === Obj2.name) {
        Obj1.splice(i, 1)
        Obj1.unshift(Obj2)
        break
    }
}

console.log(Obj1)

CodePudding user response:

You could sort by checking the properties.

const
    isEqual = (a, b) => a.Id === b.Id && a.name === b.name,
    array = [{ Id: 123, name: 'A' }, { Id: 124, name: 'B' }, { Id: 125, name: 'C' }, { Id: 126, name: 'D' }, { Id: 127, name: 'E' }],
    object = { Id: 126, name: 'D' };

array.sort((a, b) => isEqual(b, object) - isEqual(a, object));

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

Please try this

let Obj1 = [
   {
      "Id":123,
      "name":"A"
   },
   {
      "Id":124,
      "name":"B"
   },
   {
      "Id":125,
      "name":"C"
   },
   {
      "Id":126,
      "name":"D"
   },
   {
      "Id":127,
      "name":"E"
   }
]

let Obj2 = {
    "Id":126, 
    "name":"D"
}

/* 

if Obj2 isn't in the array called Obj1...
put Obj2 at the front of the Obj1 array

*/

if (Obj1.indexOf(Obj2) == -1) {
  Obj1.unshift(Obj2);
}

CodePudding user response:

This Worked for me Thanks

data.unshift(data.splice(data.findIndex(item => item.Id === Obj2.Id, 1)[0]);
  • Related