Trying to make a select filter with all the unique coins, but not getting to the end of it correctly.
When looping through data I can get a list of all the coins like this.
JavaScript
x
5
1
const uniqueCoins = data.map((item) => {
2
item.currencies.map((subItem) =>
3
console.log(subItem))
4
});
5
I also want to use the Set method and spread operator to get just unique values but I’m not sure how to combine all these.
JavaScript
1
36
36
1
const data = [
2
{
3
id: "1",
4
name: "Digitec",
5
description: "Wir akzeptieren folgende Kryptowährungen",
6
currencies: [
7
{coin: "Bitcoin"},
8
{coin: "Ethereum"},
9
{coin: "XRP"},
10
],
11
link: "webseite besuchen",
12
},
13
{
14
id: "2",
15
name: "Galaxus",
16
description: "Wir akzeptieren folgende Kryptowährungen",
17
currencies: [
18
{coin: "Bitcoin"},
19
{coin: "Monero"},
20
{coin: "XRP"},
21
],
22
link: "webseite besuchen",
23
},
24
{
25
id: "3",
26
name: "Brack.ch",
27
description: "Wir akzeptieren folgende Kryptowährungen",
28
currencies: [
29
{coin: "Litecoin"},
30
{coin: "Dogecoin"},
31
{coin: "XRP"},
32
],
33
link: "Onlineshop besuchen",
34
},
35
];
36
Advertisement
Answer
Start by combining all the coin
values from all the currencies
arrays using map
, and flatMap
, add that flattened array to a Set to dedupe the elements, and then spread the Set back out into an array.
JavaScript
1
28
28
1
const data=[{id:"1",name:"Digitec",description:"Wir akzeptieren folgende Kryptowährungen",currencies:[{coin:"Bitcoin"},{coin:"Ethereum"},{coin:"XRP"}],link:"webseite besuchen"},{id:"2",name:"Galaxus",description:"Wir akzeptieren folgende Kryptowährungen",currencies:[{coin:"Bitcoin"},{coin:"Monero"},{coin:"XRP"}],link:"webseite besuchen"},{id:"3",name:"Brack.ch",description:"Wir akzeptieren folgende Kryptowährungen",currencies:[{coin:"Litecoin"},{coin:"Dogecoin"},{coin:"XRP"}],link:"Onlineshop besuchen"}];
2
3
// Get a new array of coins for each object, and then
4
// flatten all of them into one array
5
const coins = data.flatMap(obj => {
6
return obj.currencies.map(currency => currency.coin);
7
});
8
9
// Create a set from the coins array
10
const set = new Set(coins);
11
12
// `sort and `map` over the array to produce
13
// an array of HTML for each option
14
const options = [set].sort().map(option => {
15
return `<option value=${option}>${option}</option>`;
16
});
17
18
// Add those options to a select
19
const select = `
20
<select>
21
<option disabled selected>Choose a coin</option>
22
<option disabled>----</option>
23
${options.join('')}
24
</select>
25
`
26
27
// Add that HTML to a container
28
document.body.insertAdjacentHTML('beforeend', select);
Additional documentation