Skip to content
Advertisement

How to reduce an array of object for unique key value pairs using an another array?

I have an array of object that contains different key value pairs and I’m trying to reduce this array of object using an another array.

I can refer the array that need to be reduced as the “Reducible Array” and the array I’m using to reduce as “Key array”.

Reducible Array:

[
  {
    "movie": {
      "title": "Avengers",
      "universe": "MARVEL",
      "owned": "Walt Disney"
    }
  },
  {
    "movie": {
      "title": "Captain America",
      "universe": "MARVEL",
      "owned": "Walt Disney"
    }
  },
  {
    "movie": {
      "title": "Justice League",
      "universe": "DC",
      "owned": "Warner Bros"
    }
  }
]

Key Array:

[DC, MARVEL]

The reduced array of object I’m expecting after the operation is as follows.

Expected Result:

[
  {
    "Universe": "MARVEL",
    "OwnedBy": "Walt Disney"
  },
  {
    "Universe": "DC",
    "OwnedBy": "Warner Bros"
  }
]

What are all the operations I need to perform to get the expected result?

Advertisement

Answer

Since you naturally felt to use the word reduce you must know that javascript offers such a method to reduce arrays:

const keyArray = ['DC', 'MARVEL'];
const array = [
  {
    "movie": {
      "title": "Avengers",
      "universe": "MARVEL",
      "owned": "Walt Disney"
    }
  },
  {
    "movie": {
      "title": "Captain America",
      "universe": "MARVEL",
      "owned": "Walt Disney"
    }
  },
  {
    "movie": {
      "title": "Justice League",
      "universe": "DC",
      "owned": "Warner Bros"
    }
  }
];

const reducedObject = array.reduce((carry, {movie}) => {
    const key = `${movie.universe}-${movie.owned}`;
    
    if (keyArray.includes(movie.universe) && !carry.hasOwnProperty(key)) {
        carry[key] = {universe: movie.universe, owned: movie.owned};
    }
    
    return carry;
}, {});

const reducedArray = Object.values(reducedObject);

console.log(reducedArray);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement