0

I try to search any of the value I got in an array inside an other array with lot of objects. I try to use lodash but vanilla is ok too.

My reference array is like so:

let array1 = ["value1", "value2", "value8", "value9"]

I want to find those value in this array of objects:

let array2 = [{
  key1: xxx
  key2: value1
  key3: xxxx
}, {
  key1: value2
  key2: xxxx
  key3: xxxx
}, {
  key1: xxx
  key2: xxx
  key3: value3
}]

I've tried

let finalData: []

let filterData = _.filter(array2, array1);
this.finalData = filterData

I expect to return an array with all match object:

[{
  key1: xxx
  key2: value1
  key3: xxxx
}, {
  key1: xxx
  key2: value2
  key3: xxxx
}]

I just get an empty array all the time. Do i need to combien a for each method to do that ?

BONUS: if it could return an error with an array of the not found values (value8, value9) this would be cherry on the cake.

NuoNuo LeRobot
  • 370
  • 3
  • 16

1 Answers1

1

let array1 = ["value1", "value2", "value8", "value9"];
let array2 = [
  {
    "key1": "xxx",
    "key2": "value1",
    "key3": "xxxx"
  }, {
    "key1": "xxx",
    "key2": "value2",
    "key3": "xxxx"
  },
  {
    "key1": "xxx",
    "key2": "value3",
    "key3": "xxxx"
  }
];

// copy the original array1
let noMatch = [...array1];

// iterate (and filter) through every element
// that array2 contains
let match = array2.filter(elem => {
  // iterate through every key in the element
  for (const key in elem) {
    // check if array1 has the value
    const found = array1.find(e => e === elem[key]);
    if (found) {
      // remove from noMatch the matched value
      noMatch = noMatch.filter(e => e !== found);
      // found
      return true;
    }
  }
  // Not found
  return false;
});

// matched elements
console.log('match', match);
// values that didn't match any element
console.log('noMatch', noMatch);
silentw
  • 4,835
  • 4
  • 25
  • 45