0

I have two(2) arrays, beforeArray & afterArray

const beforeArray = [
   {
    id:1, 
    name:'Alice'
   },
   {
    id:2, 
    name:'Rabbit'
   },
   {
    id:3, 
    name:'Queen'
   },
   {
    id:4, 
    name:'King'
   },
];

const afterArray = [
   {
    id:3, 
    name:'Queen'
   },
];

I'm trying to get the difference of beforeArray & afterArray like this array below:

const currentArray = [
   {
    id:1, 
    name:'Alice'
   },
   {
    id:2, 
    name:'Rabbit'
   },
   {
    id:4, 
    name:'King'
   },
];

I tried using these way but it only returns the value from let currentArray = [];:

let currentArray = [];

await afterArray.map(async item => {
    await beforeArray.filter(async find => {
        if (item.id != find.id) {
            await currentArray.map(async less => {
                if (less.id == find.id) {
                    return;
                } else {
                    currentArray = await [...currentArray, find];
                }
            });
        }
    })

console.log(currentArray);

I think it console.log(currentArray) skips the await.... How can I get the value from the awaited map and filter?

  • based on the name property are you trying to find the difference ? what is the rule for finding difference ? – Kunal Mukherjee May 15 '19 at 07:38
  • 1
    What is with all the `async` and `await`s? I don't think any of this is async code. – VLAZ May 15 '19 at 07:40
  • Possible duplicate of [How to get the difference between two arrays in Javascript?](https://stackoverflow.com/questions/1187518/how-to-get-the-difference-between-two-arrays-in-javascript) – Engineer May 15 '19 at 07:42
  • @KunalMukherjee I'm trying to remove the `{id:3, name:'Queen'}` from the `beforeArray` and pass it on to the `currentArray` – Mirai-dev00 May 15 '19 at 07:43

2 Answers2

2

Try filtering the array using Array.prototype.some like this:

const beforeArray = [{
    id: 1,
    name: 'Alice'
  },
  {
    id: 2,
    name: 'Rabbit'
  },
  {
    id: 3,
    name: 'Queen'
  },
  {
    id: 4,
    name: 'King'
  },
];

const afterArray = [{
  id: 3,
  name: 'Queen'
}];

const currentArray = beforeArray.filter(x => {
  return afterArray.some(y => y.id !== x.id && y.name !== x.name);
});

console.log(currentArray);
Kunal Mukherjee
  • 5,775
  • 3
  • 25
  • 53
-1

You should not be using the async/await until you want to wait for a promise to get resolved.

You can filter array using Array.prototype.filter and Array.prototype.find

const beforeArray = [
 {
  id:1, 
  name:'Alice'
 },
 {
  id:2, 
  name:'Rabbit'
 },
 {
  id:3, 
  name:'Queen'
 },
 {
  id:4, 
  name:'King'
 },
];

const afterArray = [
 {
  id:3, 
  name:'Queen'
 },
];

let out = beforeArray.filter(({id, name}) => !afterArray.find(r => r.id === id && r.name === name));

console.log(out)
AZ_
  • 3,094
  • 1
  • 9
  • 19