I'm having trouble wrapping my head around this, but let's say there an array with these elements:
["apple", "banana", "pear", "kiwi", "orange"]
I would like to transfer this array into:
["apple", "apple/banana", "apple/banana/pear", "apple/banana/pear/kiwi", "apple/banana/pear/kiwi/orange"]
I need this in JavaScript and I'm not sure how to achieve it.
Please note that I'm currently working with ES5.
I'm having trouble wrapping my head around this, but let's say there an array with these elements:
["apple", "banana", "pear", "kiwi", "orange"]
I would like to transfer this array into:
["apple", "apple/banana", "apple/banana/pear", "apple/banana/pear/kiwi", "apple/banana/pear/kiwi/orange"]
I need this in JavaScript and I'm not sure how to achieve it.
Please note that I'm currently working with ES5.
Share Improve this question edited Aug 9, 2018 at 12:45 halfer 20.3k19 gold badges109 silver badges202 bronze badges asked Jul 4, 2018 at 10:16 abortedaborted 4,54114 gold badges73 silver badges134 bronze badges 8- 1 Whats wrong with pear? – Timmetje Commented Jul 4, 2018 at 10:16
- 1 Downvoting because this is a question on how to elaborate an algorithm, rather than a technical difficulty with javascript. – Jose Manuel Gomez Alvarez Commented Jul 4, 2018 at 10:30
- 2 @JoseManuelGomezAlvarez I think it's a technical difficulty with Javascript as I don't know how to achieve that? – aborted Commented Jul 4, 2018 at 10:33
- 1 @JoseManuelGomezAlvarez, the question is on topic here for Stack Overflow. However, no effort has be shown by the original poster. Voting to close. – Ivan Commented Jul 4, 2018 at 10:35
- 1 @Timmetje it is formatted but it doesn't mean it's a valid question for Stack Overflow: usually, when no effort has been made (shown) by the original poster the question would be treated as a homework question and closed. – Ivan Commented Jul 4, 2018 at 10:50
7 Answers
Reset to default 5Here's a simple implementation of what you're trying to do :
ES5
var input = ["apple", "banana", "pear", "kiwi", "orange"];
var prev = '';
var output = input.map(function (el) {
el = prev + el; prev = el + '/'; return el;
});
console.log(output);
ES6
let input = ["apple", "banana", "pear", "kiwi", "orange"];
let prev= '';
let output = input.map( el => { el = prev + el; prev = el+'/'; return el})
console.log(output)
Array.map()
is meant for these problems.
The
map()
method creates a new array with the results of calling a provided function on every element in the calling array.
And while walking through the array with map
you can use join()
and slice()
to concatenate certain values from an original 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" ]
Some more explanation on what is happening in those 3 lines:
// let's write it out.
let output = input.map((el, index) => {
// If there is a previous index of this array, we need to join it with this one
if (input[index-1]) {
// all previous values including this one
let a = input.slice(0, index+1)
// concatenate them all with a seperator
let b = a.join('/');
return b;
} else {
// if not just return the element
return el;
}
})
You wrote: Please note that I'm currently working with ES5.
Unfortunately, some people do not understand anymore what is ES5 and suggest ES6 solutions (with arrow function expressions, let statements and constants).
Array.map
was added to the ECMA-262 standard in the ECMAScript 5.1 edition. It is fully supported by all modern browsers inclusive IE9.
var input = ["apple", "banana", "pear", "kiwi", "orange"],
output = input.map(function(elem, index)
{
return index > 0 ? input.slice(0, index + 1).join('/') : elem;
});
console.log(JSON.stringify(output, null, '\t'));
var fruits = ["apple", "pear", "orange", "banana"];
var i;
for( i=0; i<fruits.length; i++) {
if (i == 0){
continue;
}
var temp = fruits[i];
fruits[i] = fruits[i-1] + "/" + temp;
}
for( i=0; i<fruits.length; i++) {
print(fruits[i]);
}
Here you go!
Points to remember:
- Concatenation Operator
- For loop
- continue statement
- Arrays
var array = ["apple", "banana", "pear", "kiwi", "orange"]
var all = [];
var str ="";
for(var i=0;i< array.length;i++)
{
if(array[i-1]){
str += array[i-1]+'/';
all.push(str+array[i])
}
else all.push(array[i])
}
console.log(all);
Time to .reduce
it
This works by creating a new array, and accessing the last placed string and appending a '/'
and then the next string current
.
yourArray.reduce((newArray, current) => newArray.concat(newArray.length > 0 ? newArray[newArray.length - 1] + '/' + current : current), [])
// long version:
yourArray.reduce((newArray, current) => {
if (newArray.length > 0) {
return newArray.concat(current)
} else {
const previousString = newArray[newArray.length - 1]
return newArray.concat(previousString + '/' + current)
}
}, [])
For the ones that do use ES6 or can transpile the code to ES5 (Using i.e: Babel)
const a = ["a", "b", "c", "d", "e"];
const res = a.map((_, i) => a.slice(0, i+1).join("/"));
console.log(res);