leo
leo

Reputation: 103

How to remove duplicates with extra keys from an array

I have two arrays:

const a1=[
  {
    a:{ name: "first" }
  },
  {
    b:{ name: "second" }
  },
  {
    c:{ name: "third" }
  },
  {
    d:{ name: "fourth" }
  }
]

const a2=[
  {
    a:{ name: "first", shelf: "read" }
  },
  {
    b:{ name: "second", shelf: "current" }
  }

]

I need to check if contents of a1 is in a2 and if it exists replace it in a1 (basically shelf name is missing in a1. I need to update that in a1).

My end result should look like:

[
  {
    a:{ name: "first", shelf: "read" }
  },
  {
    b:{ name: "second", shelf: "current" }
  }
  {
    c:{ name: "third" }
  },
  {
    d:{ name: "fourth" }
  }
]

I have tried something like

const x = a1.map( ele => {
    a2.map( e =>  {
        if( e.name === ele.name ) return ele 
        else return ({ ...ele, shelf: 'none' })
    })
    return ele;
})

But since I don't have access to the inner maps return value I get the original array back. One way I though of doing this was to concatenate both arrays and use reduce the array by checking the shelf name using javascript's reduce method. Can someone help me with a better method.

Upvotes: 1

Views: 61

Answers (2)

Yann Armelin
Yann Armelin

Reputation: 711

This should do the job in a concise way:

a1.map((it)=> {
    const key = Object.keys(it)[0];
    const a2item = a2.find( (it2) => Object.keys(it2)[0]===key );
    if(a2item) {
        Object.assign(it[key], a2item[key]);
    }
    return it;
});

Please note that the elements of the original a1 array are modified.

Upvotes: 1

Ashish Ranjan
Ashish Ranjan

Reputation: 12960

I would go by first creating an Auxiliary object for "a2" and when I am looping over a1, in each loop I would check the existence of the current key in the auxiliary object.

Having an Auxiliary Object save you unnecessary loops, you only traverse both the arrays only once.

const a1 = [{a: {name: "first"}}, {b: {name: "second"}}, {c: {name: "third"}}, {d: {name: "fourth"}}];

const a2 = [{a: {name: "first", shelf: "read"}}, {b: {name: "second",shelf: "current"}}];

const dict = a2.reduce((acc, ob) => { 
  const [k, v] = Object.entries(ob)[0];
  acc[k] = v;
  return acc;
}, {});

const newA1 = a1.map((ob) => {
  const [k, v] = Object.entries(ob)[0];
  if (dict[k]) {
    Object.assign(v, dict[k]);
  }
  return {[k]: v};
});

console.log(newA1)

Upvotes: 1

Related Questions