私は次のような配列を持っています:
dateArray = [
{year:'2018', month: "01"},
{year:'2018', month: "01"},
{year:'2017', month: "02"},
{year:'2017', month: "02"}
];
その配列から一意の値を取得したいので、次のようにしてみました。
let unique = [...new Set(this.state.dateArray.map(item => item.Group))];
console.log('UNIQUE: ',unique);
このソリューションは機能しません。辞書の配列から一意の辞書を取得して、新しい配列に配置するにはどうすればよいですか?
おそらくもっとクリーンな方法がありますが、これはアレイを重複排除します。
const dateArray = [
{year:'2018', month: "01"},
{year:'2018', month: "01"},
{year:'2017', month: "02"},
{year:'2017', month: "02"}
];
const uniqueDates = [];
for (let date of dateArray){ // Use "of" to loop through an array
let unique = true; // Set a flag to handle possible unwanted items
for (let uniqueDate of uniqueDates){
if (uniqueDate.year == date.year && uniqueDate.month == date.month){
unique = false; // Both properties match, so throw up the flag
}
}
if(unique){ // Only add the item if the flag didn't go up
uniqueDates.push(date);
}
}
console.log(uniqueDates);
const uniqueDates = [];
dateArray.forEach(date => { // the argument passed to the callback stores the current item
let unique = true;
uniqueDates.forEach(uniqueDate => {
if (uniqueDate.year == date.year && uniqueDate.month == date.month){
unique = false;
}
});
if(unique){
uniqueDates.push(date);
}
});
console.log(uniqueDates);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加