Home > Software design >  Remove mirrored objects from an array
Remove mirrored objects from an array

Time:01-28

I have an issue which I dont't really know how to tackle in a good way

I have an array of objects which looks roughly like this:

[
    { name: "horse", newName: "owl" }
    { name: "owl", newName: "horse" }
    { name: "frog", newName: "dog" }
]

I want to remove "mirrored" objects from this array, in result having an array like this:

[
    { name: "frog", newName: "dog" }
]

Basically I need to find objects with opposite keys and values

More complex scenarios:

[
    { name: "horse", newName: "frog" }
    { name: "owl", newName: "horse" }
    { name: "frog", newName: "owl" }
]

    // Result: []
[
    { name: "horse", newName: "frog" }
    { name: "dog", newName: "cat" }
    { name: "owl", newName: "horse" }
    { name: "frog", newName: "owl" }
    { name: "monkey", newName: "worm" }
    { name: "cat", newName: "dog" }
]

    // Result: [{ name: "monkey", newName: "worm" }]

In the first case I would simply loop through the array and if an object like this is found:

{name: obj1.value2, newName: obj1.value1} I would splice them both

But I have no idea how to approach the more complex situation when 3 or more objects would have to be removed. Any hints?

In advance thanks for your time

CodePudding user response:

Use some to check the present value.

var array = [{
    name: "horse",
    newName: "frog"
  },
  {
    name: "dog",
    newName: "cat"
  },
  {
    name: "owl",
    newName: "horse"
  },
  {
    name: "frog",
    newName: "owl"
  },
  {
    name: "monkey",
    newName: "worm"
  },
  {
    name: "cat",
    newName: "dog"
  }
]

array.forEach(t => {

  var nameFound = array.some(a => a.name == t.newName);
  var newNameFound = array.some(a => a.newName == t.name);
  if (!nameFound && !newNameFound) {
    console.log(t);
  }
});

CodePudding user response:

you can do it by using filter function on array

var data = [
    { name: "horse", newName: "frog" },
    { name: "dog", newName: "cat" },
    { name: "owl", newName: "horse" },
    { name: "frog", newName: "owl" },
    { name: "monkey", newName: "worm" },
    { name: "cat", newName: "dog" }
];


let noMirrored = data.filter(one => {
  return (
    !data.some(element => element.name === one.newName) &&
    !data.some(element => element.newName === one.name)
  );
});

console.log(noMirrored);

  •  Tags:  
  • Related