Home > Software design >  How to return objects that are repeated in all subarrays from the main array in Javascript
How to return objects that are repeated in all subarrays from the main array in Javascript

Time:11-27

I'm looking for a function to select the objects that are repeated in all subarrays from the main array

array = [
  [{"post_id": 86403},{"post_id": 86404},{"post_id": 86405}],
  [{"post_id": 86403},{"post_id": 86404},{"post_id": 86407}],
  [{"post_id": 86403},{"post_id": 86404},{"post_id": 86409}]
];

I expect it return {"post_id": 86403} and {"post_id": 86404} that are repeated in every subarray

I found this but it's not dynamic and the arrays must be entered manually also it has string like "Lorem" instead of object like {"post_id": 86403}

var array1 = ["Lorem", "ipsum", "dolor"],
    array2 = ["Lorem", "ipsum", "quick", "brown", "foo"],
    array3 = ["Jumps", "Over", "Lazy", "Lorem"],
    array4 = [1337, 420, 666, "Lorem"],
    data = [array1, array2, array3, array4],
    result = data.reduce((a, b) => a.filter(c => b.includes(c)));

console.log(result);

CodePudding user response:

You can use the same pattern as in the solution you found: it is a matter of matching post_id properties instead of the array values themselves:

  • The filter callback should retrieve the post_id from the iterated item
  • The includes call should be replaced with some, whose callback will grab the other post_id and compare it

var data = [
  [{"post_id": 86403},{"post_id": 86404},{"post_id": 86405}],
  [{"post_id": 86403},{"post_id": 86404},{"post_id": 86407}],
  [{"post_id": 86403},{"post_id": 86404},{"post_id": 86409}]
];
var result = data.reduce((a, b) => 
   a.filter(({post_id: c}) => b.some(({post_id}) => post_id == c))
);

console.log(result);

  • Related