简体   繁体   中英

JavaScript Sort Array through value and display in HTML table

So, I have this list and I need to sort them after a certain brand of car. For example, Audi. And display them in an HTML table, one column with names and the other one with vehicles owned, the first ones being the Audi vehicle owners and then the others. How can I do that?

const people = [
  { name: "Ana", cars: "Audi" },
  { name: "Victoria", cars: ["Audi", "BMW"] },
  { name: "Grace", cars: ["Volkwagen", "Audi"] },
  { name: "Dan", cars: ["Opel", "Volkswagen"] },
  { name: "Josh", cars: ["Opel"] },
  { name: "John", cars: ["BMW", "Jaguar"] },
  { name: "Damon", cars: ["Renault", "Mercedes", "Audi"] },
];

Thank you!

Using reduce() you could group the car's owners.

 const people = [ { name: "Ana", cars: ["Audi"] }, { name: "Victoria", cars: ["Audi", "BMW"] }, { name: "Grace", cars: ["Volkswagen", "Audi"] }, { name: "Dan", cars: ["Opel", "Volkswagen"] }, { name: "Josh", cars: ["Opel"] }, { name: "John", cars: ["BMW", "Jaguar"] }, { name: "Damon", cars: ["Renault", "Mercedes", "Audi"] } ]; var brands = people.reduce((acc, o) => { o.cars.forEach(c => { if (!(c in acc)) acc[c] = []; acc[c].push(o.name); }); return acc; }, {}); var cont = document.getElementById("brands"); for (let b in brands) { var brand = document.createElement("p"); brand.innerHTML = "<b>" + b + "</b>: " + brands[b].join(" "); cont.appendChild(brand); } //console.log(brands); 
 <p>Brands and owners</p> <div id="brands"> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM