[英]Remove duplicates from a multidimensional array
我發現了與我遇到的問題有關的問題,但我還沒有找到適合我的解決方案。 我有這個數組: [[1, red], [2, green], [3, red], [3, blue], [5, green]]
,我需要它返回[[1, red], [2, green], [3, blue]
。 我需要代碼執行的操作是遍歷數組,僅查找匹配的顏色,而不是數字,並消除整個索引。
我已經嘗試過這樣的事情
var uniqueArray = colors.filter(function(item, pos) {
return colors.indexOf(item) == pos;
});
我認為這段代碼正在搜索完全匹配,而我只需要部分匹配。 因此,基本上,我將如何修改.filter()
來消除部分重復(僅匹配顏色)?
如果需要提供更多信息,請告訴我。
我將使用for
循環來填充新的唯一數組:
var old_array = [[1, red], [2, green], [3, red], [3, blue], [5, green]],
old_count = old_array.length,
unique_array = [], check_array = [], i = 0;
for(; i < old_count; i++) {
if (check_array.indexOf(old_array[i][1]) === -1) {
check_array.push(old_array[i][1]);// this array is filled with new colors, and used for checking
unique_array.push(old_array[i]);
}
}
您可以使用具有顏色的哈希表,並對所需項目使用Array#filter
。
var data = [[1, 'red'], [2, 'green'], [3, 'red'], [3, 'blue'], [5, 'green']], result = data.filter(function (a) { if (!this[a[1]]) { return this[a[1]] = true; } }, Object.create(null)); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
// Parameter marr: multidimensional array
function removeSameColors(marr){
var carr = [];
var rarr = [];
var j = -1;
for(var i = 0, l = marr.length; i < l; i++){
if(carr[marr[i][1]] !== true){
carr[marr[i][1]] = true;
rarr[++j] = marr[i];
}
}
return rarr;
}
那應該以非常低的執行時間解決您的問題。
我只是跟蹤傳遞到濾鏡中的對象中的唯一顏色,因為作為哈希,它保證是唯一的。 如果對象不具有該顏色名稱的屬性,它將從過濾器返回它。 否則,它將忽略該項目。
var colors = [[1, "red"], [2, "green"], [3, "red"], [3, "blue"], [5, "green"]];
var uniqueArray = colors.filter(function(item, pos) {
if (!this.hasOwnProperty(item[1])) {
return this[item[1]] = true;
}
return false;
}, {});
如預期的那樣,這將為您提供uniqueArray = [[1,"red"],[2,"green"],[3,"blue"]]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.