0

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?

user1235285
  • 87
  • 2
  • 17

2 Answers2

0

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))

Pankaj Saini
  • 752
  • 6
  • 7
0
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.

user1235285
  • 87
  • 2
  • 17