2017-10-13 96 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);