0

I have two sample arrays below.

let arr1 = [
  { key: "WIHUGDYVWJ", className: "science" },
  { key: "qwljdhkuqwdnqwdk", className: "english" },
  { key: "likubqwd", className: "robotics" }
];
let arr2 = [
  { key: "WIHUGDYVWJ", title: "math" },
  { key: "qwljdhkuqwdnqwdk", title: "english" },
  { key: "likubqwd", title: "robotics" }
];
  1. How can I filter arr1 to get only items that have 'className' value that matches arr2's item's 'title' value? (expecting only items with 'english' and 'robotics' to remain)

  2. How can I filter arr1 to get only items that have 'className' value that do not match arr2's item's 'title' value? (expecting only items with 'science' to remain)

Thanks!

1 Answers1

0

let arr1 = [
  { key: "WIHUGDYVWJ", className: "science" },
  { key: "qwljdhkuqwdnqwdk", className: "english" },
  { key: "likubqwd", className: "robotics" },
  { key: "abcd", className: "history" }
];

let arr2 = [
  { key: "WIHUGDYVWJ", title: "math" },
  { key: "qwljdhkuqwdnqwdk", title: "english" },
  { key: "likubqwd", title: "robotics" }
];

// q1 answer
console.log(arr1.map(arr1Item => arr2.filter(arr2Item => arr1Item.className === arr2Item.title)).flat());

// q2 answer
console.log(arr1.filter(arr1Item => !arr2.some(arr2Item => arr2Item.title === arr1Item.className)));

i wrote without using a for, if/else statement as much as possible. this code may not be the best. i think it could be more improved.

I hope my answer is helpful

  • Thanks so much @dangerousmanleesanghyeon! accepted the answer.. still learning to grasp filtering within mappings and this was very helpful. I was also trying to do the reverse where I'm trying to filter out those that do not match. ie. arr1 showing only the 'science' item as a result of the filter. replacing === to !== didnt seem to work, any advice? I've updated the question to two parts so that others can refer to as well! thanks! – hungryhungrydev Mar 04 '22 at 03:49
  • @hungryhungrydev i just edited answer – dangerousmanleesanghyeon Mar 04 '22 at 04:59
  • huge thanks mate! it's very concise and works well. will reach out again if i have troubles wrapping my head around it. accepted the updated answer! – hungryhungrydev Mar 04 '22 at 06:05
  • hey just learning that .find() returns the first element that matches the criteria.. so if i add another item say "history" in arr1 it only still returns 'science'. – hungryhungrydev Mar 04 '22 at 06:19
  • @hungryhungrydev i just found better way – dangerousmanleesanghyeon Mar 04 '22 at 06:27
  • FANCY! awesome, it is working as expected now. Learnt about .some() now :) thanks again @dangerousmanleesanghyeon ! – hungryhungrydev Mar 04 '22 at 07:25