Saturday, June 25, 2022

JS Map, Join Methods & The Spread Operator

The Javascript Array map method takes each element of an array and maps it to a new value. The mapping is done by the callback function that is passed to map . These values are returned in a new array. The original array is unchanged.
const my_array = [1,2,3,4];
const new_array = function(v) { return v+2 } );
// Resulting new_array will be: [3,4,5,6]
Typically the callback function is written as an arrow function:
const my_array = [1,2,3,4];
const new_array = v => v+2 );
Suppose we have a list of words or phrases and we want to wrap each one in a li element:
const list = ["apples", "pears", "grapes", "strawberries"];
const html_elements = => '<li>${v}</li>');
We can then take the html_elements array and convert it to a string using the Array join method which concatenates each element into one string, separating each string by a "join string" that is passed into join as the first parameter:
let html = html_elements.join(' ');
The line above will put a space between each element. We don't need that space, so a better way to do it is to join with an empty string:
let html = html_elements.join('');
This gives us a string with all the li elements, but we'd still need to wrap a ul or ol element around these li's. We could do it like this:
let html = '<ul>'+html_elements.join('')+'</ul>';
But I want to demonstrate the spread operator (...), so I'll show another way:
let html = ['<ul>', ...html_elements, '<ul>'].join(''); 
In this line of code I'm first building an array where the first and last elements are the opening and closing ul tags. The elements in the middle come from the html_elements array. To place these elements in the array we use the spread operator. The spread operator "spreads out" the elements of an array as if you had manually typed them into the array:
let html = ['<ul>', "<li>apples</li>", "<li>pears</li>", "<li>grapes</li>", "<li>strawberries</li>", '<ul>'].join(''); 

Image: Mateusz Feliksik, CC-BY-SA 3.0

Post a Comment

Note: Only a member of this blog may post a comment.