[Vuejs]-Compute similarities in arrays

0👍

You could check the arrays if the objects are included in all arrays and filter the arrays by using the common part.

var $scope = { presentOnColor: ['A', 'B', 'C'], presentOnStyle: ['B', 'C', 'D'], presentOnTechnique: ['B', 'C', 'F'] },
    presentFilter = [$scope.presentOnColor, $scope.presentOnStyle, $scope.presentOnTechnique].reduce(function(a, b) {
        return a.filter(function(c) {
            return b.indexOf(c) !== -1;
        });
    });

console.log(presentFilter);

ES6

var $scope = { presentOnColor: ['A', 'B', 'C'], presentOnStyle: ['B', 'C', 'D'], presentOnTechnique: ['B', 'C', 'F'] },
    presentFilter = [$scope.presentOnColor, $scope.presentOnStyle, $scope.presentOnTechnique]
        .reduce((a, b) => a.filter(c => b.includes(c)));

console.log(presentFilter);

0👍

Here is very nicer more efficient way of solving the issue. I assumed A, B, C as the characters in he array. If this is happened to be the object give me properties of the object. If you get the idea then its okay.

// Given input as these 3 arrays

const presentOnColor = ['A', 'B', 'C']
const resentOnStyle = ['B', 'C', 'D'];
const presentOnTechnique = ['B', 'C', 'F'];

// Expected outcome
// const presentFilter = ['B', 'C'];

const arrayMap = [
    ...presentOnColor,
    ...resentOnStyle,
    ...presentOnTechnique
].reduce((object, item) => {
    object[item] = (object[item] || 0) + 1;
    return object;
}, {});

const presentFilter = Object.keys(arrayMap).filter(item => arrayMap[item] === 3);

console.log('presentFilter: ', presentFilter);

Leave a comment