计算数组中的相似性

时间:2017-10-13 07:49:16

标签: javascript arrays vue.js

我正忙着制作过滤器。现在我想比较5个包含对象的数组。在计算变量中,我只想拥有在所有数组中找到的对象。

这些是创建不同过滤器(包含对象的数组)的计算变量

computed: 
    filteredOnColor () {
      this.presentOnColor = []
      for (var p = 0; p < this.paintings.length; p++) {
        for (var i = 0; i < this.kleur.length; i++) {
          if (this.kleur.length > 0 && this.paintings[p].kleur.includes(this.kleur[i])) {
            this.presentOnColor.push(this.paintings[p].title)
          }
        }
      }
    },
    filteredOnTechnique () {
      this.presentOnTechnique = []
      for (var p = 0; p < this.technique.length; p++) {
        for (var i = 0; i < this.technique.length; i++) {
          if (this.technique.length > 0 && this.paintings[p].technique.includes(this.technique[i])) {
            this.presentOnTechnique.push(this.paintings[p].title)
          }
        }
      }
    },
    filteredOnStyle () {
      this.presentOnStyle = []
      for (var p = 0; p < this.style.length; p++) {
        for (var i = 0; i < this.style.length; i++) {
          if (this.style.length > 0 && this.paintings[p].style.includes(this.style[i])) {
            this.presentOnStyle.push(this.paintings[p].title)
          }
        }
      }
    },

RAW DATA

presentOnColor: [A,B,C]
presentOnStyle: [B,C,D
presentOnTechnique: [B,C,F]

presentFilter: [B,C]

2 个答案:

答案 0 :(得分:0)

如果对象包含在所有数组中,您可以检查数组,并使用公共部分过滤数组。

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

答案 1 :(得分:0)

这是解决问题的更有效方法。我假设A,B,C为他数组中的字符。如果碰巧是对象给我对象的属性。如果你明白这个想法就可以了。

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