Array.map()
is the perfect solution for scenarios like this.
The map()
function generates a new array by applying a specified function to each element in the original array.
When using map
on an array, you can incorporate join()
and slice()
to merge specific values from the initial array.
let input = ["apple", "banana", "pear", "kiwi", "orange"];
let output = input.map((el, index) => {
return (input[index-1]) ? input.slice(0, index+1).join('/') : el;
})
output:
Array [
"apple",
"apple/banana",
"apple/banana/pear",
"apple/banana/pear/kiwi",
"apple/banana/pear/kiwi/orange"
]
Further explanation of the logic behind those 3 lines:
// breaking it down.
let output = input.map((el, index) => {
// Check if there is a previous index in this array, then merge it with the current one
if (input[index-1]) {
// all the previous elements including the current one
let a = input.slice(0, index+1)
// join them together with a separator
let b = a.join('/');
return b;
} else {
// if not, just return the element itself
return el;
}
})