简体   繁体   中英

Next array element must start off with previous

I have an array: ['cart', 'registration'] I want to map him to ['cart', 'cart/registration'] I tried to do that with .reduce, but prev is just a letter

arr.reduce((acc, cur, i) => {  
  let prev = acc[i]
  console.log(prev)
})

You could slice the array and take a subset of the array.

 var array = ['a', 'b', 'c'], result = array.map((_, i, a) => a.slice(0, i + 1).join('/')); console.log(result); 

Or store the last value

 var array = ['a', 'b', 'c'], result = array.map((last => v => last += (last && '/') + v)('')); console.log(result); 

reduce isn't the right tool for this. A simple loop (in any of the varied forms it can take) is. Here's the for loop version:

 const array = ['cart', 'registration', 'third']; for (let i = 1; i < array.length; ++i) { array[i] = array[i - 1] + "/" + array[i]; } console.log(array); 

acc is the value returned by the previous accumulator, or in the first iteration it is either the initial value passed as a second argument to .reduce or if no initial value is passed the iteration will start with the second element and the first element gets passed as acc . Thats what happens in your case, so acc is "cart" , curr is "registration" , i is 1, and therefore acc[i] is "cart"[1] which is "a" . Just take acc as a whole instead.

  const result = [arr[0]];

  arr.reduce((acc, cur, i) => result[i] = acc + "/" + cur);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM