Home > other >  How can I find similar objects in multiple array javascript?
How can I find similar objects in multiple array javascript?

Time:07-28

Facing an issue in filter. New in javascript. I can explain the problem with an example. Here is an example I have three arrays of different size and objects I want to get the common object of them all

var arrays = [
    [
      {
        "id": "5",
        "Name" : "Actor 5"
      }
    ],
    [
      {
        "id": "5",
        "Name" : "Actor 5"
      },
      {
        "id": "6",
        "Name" : "Actor 6"
      }
    ],
    [
      {
        "id": "3",
        "Name" : "Actor 3"
      },
      {
        "id": "4",
        "Name" : "Actor 4"
      },
      {
        "id": "5",
        "Name" : "Actor 5"
      }
    ]
];

The answer should be

[
      {
        "id": "5",
        "Name" : "Actor 5"
      }
]

I tried:

var result = arrays.shift().filter(function(v.Name) {
  return arrays.every(function(a) {
    return a.indexOf(v.Name) !== -1;
  });
});

CodePudding user response:

  • You can't put v.Name in a parameter list, it can only contain variable names or destructuring patterns. You should put v in the parameter list, then use v.Name in the function body. Or you could use the destructuring pattern {Name}.
  • You can't use a.IndexOf(v.Name), because a is an array of objects, but v.Name is a string. Use a.some(el => el.Name = v.Name) to test if the name is in any of the objects in the array.

var arrays = [
  [{
    "id": "5",
    "Name": "Actor 5"
  }],
  [{
      "id": "5",
      "Name": "Actor 5"
    },
    {
      "id": "6",
      "Name": "Actor 6"
    }
  ],
  [{
      "id": "3",
      "Name": "Actor 3"
    },
    {
      "id": "4",
      "Name": "Actor 4"
    },
    {
      "id": "5",
      "Name": "Actor 5"
    }
  ]
];

var result = arrays.shift().filter(v =>
  arrays.every(subarray => subarray.some(el => el.Name == v.Name)));

console.log(result);

CodePudding user response:

You could use reduce to find the duplicated object.

var array = [
  [{
    "id": "5",
    "Name": "Actor 5"
  }],
  [{
      "id": "5",
      "Name": "Actor 5"
    },
    {
      "id": "6",
      "Name": "Actor 6"
    }
  ],
  [{
      "id": "3",
      "Name": "Actor 3"
    },
    {
      "id": "4",
      "Name": "Actor 4"
    },
    {
      "id": "5",
      "Name": "Actor 5"
    }
  ]
];

array.reduce((prev, curr, index, currentArray) => {
  try {
    for (let arr of currentArray) {
      if (`[${JSON.stringify(curr[0])}]` === JSON.stringify(arr)) {
        console.log(curr[0])
      }
    }
  } catch (e) {
    console.log(e)
  }
})

  • Related