2017-10-13 89 views
0

我忙于制作滤镜。现在我想比较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] 
+1

请过滤后添加原始数据和想要的结果。 –

+0

我添加了我的原始数据。 presentFilter是我想要的。 – Fenno

+0

计算属性意味着返回一个值。为什么在每个计算属性的方法中设置不同的数据属性?由于只有在计算属性被访问时才会调用这些方法,所以您的数据属性可能没有按照您期望的方式设置。 – thanksd

回答

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

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