Cookie Consent by Free Privacy Policy Generator 📌 Use Array.reduce() to fill <select>


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


💡 Newskategorie: 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>


📈 56.3 Punkte

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


📈 35.18 Punkte

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


📈 29.9 Punkte

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


📈 28.08 Punkte

✅ Fun with Array.prototype.fill()


📈 27.75 Punkte

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


📈 26.87 Punkte

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


📈 26.87 Punkte

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


📈 25.69 Punkte

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


📈 25.69 Punkte

✅ SELECT - INSERT INTO SELECT


📈 25.69 Punkte

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


📈 25.69 Punkte

✅ SELECT * FROM S3 | Query data via S3 Select


📈 25.69 Punkte

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


📈 25.69 Punkte

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


📈 24.01 Punkte

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


📈 24.01 Punkte

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


📈 22.67 Punkte

✅ Array.reduce() in JavaScript


📈 22.67 Punkte

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


📈 22.67 Punkte

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


📈 22.67 Punkte

✅ The Power Of Array.reduce()🐐


📈 22.67 Punkte

✅ Array.reduce() is Goated 🐐✨


📈 22.67 Punkte

✅ JavaScript Array Tutorial – Array Methods in JS


📈 22.33 Punkte

✅ Bash For Loop Array: Iterate Through Array Values


📈 22.33 Punkte

✅ ES6 Map an Array of Objects to Return an Array of Objects With New Keys


📈 22.33 Punkte

✅ Learn the JavaScript Array.every() and Array.some() methods


📈 22.33 Punkte

✅ How to Create an Array in Java – Array Declaration Example


📈 22.33 Punkte

✅ FFmpeg Array Access MXF File Out-of-Array memory corruption


📈 22.33 Punkte

✅ JavaScript Sort Array - How to Sort an Array Accurately


📈 22.33 Punkte

✅ FFmpeg Array Access MXF File Out-of-Array Pufferüberlauf


📈 22.33 Punkte

✅ Convert 1d Array to 2d Array Python


📈 22.33 Punkte

✅ Microsoft Edge Chakra JIT Array.prototype.reverse Array Type Confusion


📈 22.33 Punkte

✅ Bubble Sort: Given an Array of Unsorted Items, Return A Sorted Array


📈 22.33 Punkte

✅ How to pass array in another array of objects?


📈 22.33 Punkte

✅ Microsoft Edge Chakra JIT Array.prototype.reverse Array Type Confusion


📈 22.33 Punkte

✅ Merge array-like objects by Array.prototype.concat()


📈 22.33 Punkte











matomo

Datei nicht gefunden!