Lädt...

🔧 Use Array.reduce() to fill <select>


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

I have a list of colors sitting in my database and a <select> HTML element where I want to use these colors as <option>s.

Colors

I get the values from the database and store them in a variable.

const colors = [
    {val: "1", name: "Black"},
    {val: "2", name: "Red"},
    {val: "3", name: "Yellow"},
    {val: "4", name: "Green"},
    {val: "5", name: "Blue"},
    {val: "6", name: "White"}
]

Generate options with Array.reduce()

With return in the reducer callback

const colorOptions = colors.reduce(
    (options, color) => {
        options.push(`<option value="${color.val}">${color.name}</option>`)
        return options
    }, []
)

Without the return word in the reducer callback

We use Grouping ( ) and Comma (,) operators for one-liner implementation.
Identation is added for better human readability.

const colorOptions = colors.reduce(
    (options, color) => (
        options.push(`<option value="${color.val}">${color.name}</option>`),
        options
    ), []
)

Resulting colorOptions

[
    '<option value="1">Black</option>', 
    '<option value="2">Red</option>', 
    '<option value="3">Yellow</option>', 
    '<option value="4">Green</option>', 
    '<option value="5">Blue</option>', 
    '<option value="6">White</option>'
]

Sort before reducing

You can also sort on val or name before Array.reduce().

const colors = [
    {val: "1", name: "Black"},
    {val: "2", name: "Red"},
    {val: "3", name: "Yellow"},
    {val: "4", name: "Green"},
    {val: "5", name: "Blue"},
    {val: "6", name: "White"}
].sort(
    (a, b) => a.name.localeCompare(b.name)
)

// colors => [
//     '<option value="1">Black</option>', 
//     '<option value="5">Blue</option>', 
//     '<option value="4">Green</option>', 
//     '<option value="2">Red</option>', 
//     '<option value="6">White</option>', 
//     '<option value="3">Yellow</option>'
// ]

Use DocumentFragment to fill in <select>

We have a <select> on a page which is currently empty.

<select id="colors-select"></select>

We can use the DocumentFragment interface to load <select> with options as nodes.

Create DocumentFragment

const fragment = document.createRange().createContextualFragment(
    colorOptions.join('')  // convert colors array to string
)

Fill in <select>

document.getElementById('colors-select').appendChild(fragment)

Result

<select id="colors-select">
    <option value="1">Black</option>
    <option value="5">Blue</option>
    <option value="4">Green</option>
    <option value="2">Red</option>
    <option value="6">White</option>
    <option value="3">Yellow</option>
</select>

Full code snippet

const colors = [
    {val: "1", name: "Black"},
    {val: "2", name: "Red"},
    {val: "3", name: "Yellow"},
    {val: "4", name: "Green"},
    {val: "5", name: "Blue"},
    {val: "6", name: "White"}
].sort(
    (a, b) => a.name.localeCompare(b.name)
)

const colorOptions = colors.reduce(
    (options, color) => (
        options.push(`<option value="${color.val}">${color.name}</option>`),
        options
    ), []
).join('')

const fragment = document.createRange().createContextualFragment(colorOptions)

document.getElementById('colors-select').appendChild(fragment)
...

🔧 Use Array.reduce() to fill <select>


📈 52.17 Punkte
🔧 Programmierung

🔧 Select Element in Array() to a new Array() JavaScript


📈 31.66 Punkte
🔧 Programmierung

🔧 Upcoming JavaScript Features: Simplifying Array Combinations with `Array.zip` and `Array.zipKeyed`


📈 29.55 Punkte
🔧 Programmierung

🕵️ SQLite up to 3.34.0 SELECT Query src/select.c use after free


📈 27.64 Punkte
🕵️ Sicherheitslücken

📰 How to Fill the Void in NetOps Visibility to Reduce Risk


📈 26.63 Punkte
📰 IT Security Nachrichten

🔧 Fun with Array.prototype.fill()


📈 25.66 Punkte
🔧 Programmierung

🔧 How to Use JavaScript's Array reduce() Method – Explained with Examples


📈 24.4 Punkte
🔧 Programmierung

🔧 Array methods and when to use them, forEach, map, reduce


📈 24.4 Punkte
🔧 Programmierung

🔧 SQL "SELECT INTO" vs "INSERT INTO SELECT" statements.


📈 23.91 Punkte
🔧 Programmierung

🕵️ CVE-2024-9440 | Slim Select up to 2.9.0 select.ts:createOption text cross site scripting


📈 23.91 Punkte
🕵️ Sicherheitslücken

🔧 Hierarchical filter on Select tags & Select.Option of Ant Design


📈 23.91 Punkte
🔧 Programmierung

🔧 SELECT - INSERT INTO SELECT


📈 23.91 Punkte
🔧 Programmierung

🔧 SQL SELECT Statement – How to Select Data from a Database


📈 23.91 Punkte
🔧 Programmierung

🔧 SELECT * FROM S3 | Query data via S3 Select


📈 23.91 Punkte
🔧 Programmierung

🪟 A collection of the best bed upgrades for Maker Select v2 and Select Plus 3


📈 23.91 Punkte
🪟 Windows Tipps

🐧 If I were to select the worst Linux syscall, my selection would be select


📈 23.91 Punkte
🐧 Linux Tipps

🔧 When to use if-else, switch-case, or functions like Array.prototype.includes() or Array.prototype.find()


📈 23.43 Punkte
🔧 Programmierung

🐧 Select the Values of One Property on all Objects of an Array in PowerShell


📈 21.81 Punkte
🐧 Linux Tipps

🔧 Select Minimum indices having sum in first and second Array at least X and Y


📈 21.81 Punkte
🔧 Programmierung

🔧 What is Array.reduce in JavaScript?


📈 20.67 Punkte
🔧 Programmierung

🔧 What is Array.reduce in JavaScript?


📈 20.67 Punkte
🔧 Programmierung

🔧 Map(), Filter(), Reduce() javascript array method


📈 20.67 Punkte
🔧 Programmierung

🔧 JavaScript Array Methods: Sort, Map, Filter, and Reduce


📈 20.67 Punkte
🔧 Programmierung

🔧 Mastering Array Methods in JavaScript: map, filter, and reduce


📈 20.67 Punkte
🔧 Programmierung

🔧 Mastering JavaScript's Array Powerhouses: forEach, map, filter, reduce, spread, and rest


📈 20.67 Punkte
🔧 Programmierung

🔧 Understanding Array.reduce()


📈 20.67 Punkte
🔧 Programmierung

🔧 Understanding JavaScript Array Methods: forEach, map, filter, reduce, and find


📈 20.67 Punkte
🔧 Programmierung

🔧 The Power Of Array.reduce()🐐


📈 20.67 Punkte
🔧 Programmierung

🔧 Array.reduce() is Goated 🐐✨


📈 20.67 Punkte
🔧 Programmierung

🔧 Mastering JavaScript Array Manipulation: Map, Filter, and Reduce.


📈 20.67 Punkte
🔧 Programmierung

🔧 Array.reduce() in JavaScript


📈 20.67 Punkte
🔧 Programmierung

🐧 How to Call reduce on an Array of Objects to Sum Their Properties?


📈 20.67 Punkte
🐧 Linux Tipps

🔧 A guide to Object.groupBy: An alternative to Array.reduce


📈 20.67 Punkte
🔧 Programmierung

🐧 Convert 1d Array to 2d Array Python


📈 19.7 Punkte
🐧 Linux Tipps

🔧 2022. Convert 1D Array Into 2D Array


📈 19.7 Punkte
🔧 Programmierung