skip to Main Content

Is it possible to return matching values by comparing JSON arrays. For example;

0 : ['cat1', 'cat2']
1 : ['cat2', 'cat3']
2 : ['cat2', 'cat4']

The above should return 'cat2' as that exists in all 3 arrays.

EDIT: I found this snippet (Finding matches between multiple JavaScript Arrays) which appears to do the first part;

var result = obj.shift().filter(function(v) {
  return obj.every(function(a) {
    return a.indexOf(v) !== -1;
  });
});

console.log(result);

However, if an array is added that has no matches, this should return false and no results;

0 : ['cat1', 'cat2']
1 : ['cat2', 'cat3']
2 : ['cat2', 'cat4']
3 : ['cat5']

Is this possible?

2

Answers


  1. Chosen as BEST ANSWER
    var result = obj.shift().filter(function(v) {
      return obj.every(function(a) {
        return a.indexOf(v) !== -1;
      });
    });
    
    console.log(result);
    

    Is actually the answer in this case.


  2. you can easily do that using python code, here’s an example:

    array_list = [
        ['cat1', 'cat2'],
        ['cat2', 'cat3'],
        ['cat2', 'cat4']
    ]
    
    
    def find_common_words(array_list):
        if len(array_list) == 0:
            return []
    
        common_words = set(array_list[0])
        for array in array_list[1:]:
            common_words = common_words.intersection(array)
        return list(common_words)
    
    
    print(find_common_words(array_list))
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search