有帶有注釋、時間條目的物件,想要洗掉所有(所有,抱歉重復這部分,我經歷了很多例子,它們都只洗掉了第二個、第三個等重復項,但它們包括第一個重復項)具有相同時間的筆記重復從中。
好吧,我需要將唯一的與重復的分開,我已經設法使用我在 StackOverflow 上找到的這段代碼從中獲取所有重復,
const allNotes = [
{
"note": 69,
"time": 0
},
{
"note": 57,
"time": 0
},
{
"note": 60,
"time": 1.5
},
{
"note": 64,
"time": 2
},
{
"note": 69,
"time": 2.5
},
{
"note": 71,
"time": 3
},
{
"note": 52,
"time": 3
},
{
"note": 64,
"time": 4.5
},
{
"note": 68,
"time": 5
},
{
"note": 71,
"time": 5.5
}
]
const getDuplicates = () => {
const values = allNotes;
const unique = new Object;
const lookup = values.reduce((a, e) => {
a[e.time] = a[e.time] || 0;
return a;
}, {});
const duplicates = values.filter(e => lookup[e.time]);
console.log(duplicates);
}
這段代碼就像它產生的魅力一樣作業
[
{
"note": 69,
"time": 0
},
{
"note": 57,
"time": 0
},
{
"note": 71,
"time": 3
},
{
"note": 52,
"time": 3
}
]
仍然需要能夠獲得唯一的時間條目,需要這個結果
[
{
"note": 60,
"time": 1.5
},
{
"note": 64,
"time": 2
},
{
"note": 69,
"time": 2.5
},
{
"note": 64,
"time": 4.5
},
{
"note": 68,
"time": 5
},
{
"note": 71,
"time": 5.5
}
]
uj5u.com熱心網友回復:
我猜你正在尋找這樣的東西:
array.filter(a => array.filter(b => a.time === b.time).length === 1)
// filter array and sort for duplicates, just keep element if time-property is unique
請參閱下面的作業示例:
const allNotes=[{note:69,time:0},{note:57,time:0},{note:60,time:1.5},{note:64,time:2},{note:69,time:2.5},{note:71,time:3},{note:52,time:3},{note:64,time:4.5},{note:68,time:5},{note:71,time:5.5}];
const res = allNotes.filter(a => allNotes.filter(b => a.time === b.time).length === 1);
console.log(res);
uj5u.com熱心網友回復:
您已經解決了您的問題,因為您能夠挑選出重復項。只過濾相反的。
const uniqueValues = values.filter(e => !lookup[e.time]);
uj5u.com熱心網友回復:
const _dedupArr: any[] = [];
allNotes.forEach((v, i) => {
const find = _dedupArr.find(d => d.time == v.time);
if(!find) {
_dedupArr.push(v);
}
});
console.log('_dedupArr', _dedupArr);
uj5u.com熱心網友回復:
不是一個高性能的解決方案,但它絕對是一個簡單的解決方案......將每個物件轉換為一個基元,然后可以將這些基元分配給一個映射,并且只能檢索值。
const allNotes = [
{
"note": 69,
"time": 0
},
{
"note": 57,
"time": 0
},
{
"note": 60,
"time": 1.5
},
{
"note": 64,
"time": 2
},
{
"note": 69,
"time": 2.5
},
{
"note": 71,
"time": 3
},
{
"note": 52,
"time": 3
},
{
"note": 64,
"time": 4.5
},
{
"note": 68,
"time": 5
},
{
"note": 71,
"time": 5.5
},
];
const uniqueMap = new Map();
allNotes.forEach(value => uniqueMap.set(
// Any conversion to primitive is fine, JSON.stringify too
`${value.note}-${value.time}`,
value,
));
console.log(Array.from(uniqueMap.values()));
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/425941.html
標籤:javascript 目的 重复 独特的
