[英]Compare two Objects in a list using lambda in javascript
我想我可以用大約 20 行代碼自己完成這項工作。 但我認為它可以是單行的。
假設我們有一個帶有 1,2 或 3 個輪子的汽車列表。
汽車[ ] = [C1,C2,C3,C4,C5,C6]
C1-C3只有一個輪子,C4兩個,C5-C6三個。
class Car{
constructor(wheels){
this.wheels = wheels;
}
}
我想要這個結果:
FilteredCars[ ] = [[C1,C2,C3],[C4],[C5,C6]]
或者
FilteredCars[ ] = [[C1,C2,C3], [C5,C6]
=> 我需要“輪子”中哪些對象具有相同值的信息
輪子是我項目中的字符串,可能有 48 個不同的值,所以我需要比較 carX === carY
我的“嘗試”就像(“偽代碼”):
Cars.filter(carx =>
FilteredCars.add(Cars.filter (cary =>
carx.wheels === cary.wheels).toList()));
.
首先,您按輪子數對汽車進行分組,然后在每個組中抓取汽車
你可以像這樣在一行中做到這一點
let id = 0; class Car { constructor(wheels) { this.id = ++id; this.wheels = wheels; } } const data = [ new Car("1"), new Car("1"), new Car("1"), new Car("2"), new Car("3"), new Car("3"), ]; const res = [...data.reduce((acc, el) => acc.set(el.wheels, [...(acc.get(el.wheels) || []), el]), new Map()).values()]; console.log(res);
根據我從您的問題中了解到的情況。 你可以簡單地做
const Cars = [C1,C2,C3,C4,C5,C6]
const FilteredCars =[Cars.filter(car=>car.wheels===1),Cars.filter(car=>car.wheels===2),Cars.filter(car=>car.wheels===3)]
你會得到 [[C1,C2,C3],[C4],[C5,C6]] 這種結果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.