I have an array with 1000 random, fake addresses. But each address is split into 2 different arrays. for example:
[['123 main street'], ['San Diego, CA, 92101'],['22 washington ave'],['Miami, FL, 56624']]
My goal is to either mutate the current array or just create a new array with the following:
[['123 main street, San Diego, CA, 92101'],['22 washington ave, Miami, FL, 56624']]
I want to do this without using the traditional- for(let i = 1....).
I currently have the following:
const addressesFinal = addressesBad
.map(function (cur, i, arr) {
return [arr[i], arr[i + 1]];
})
.filter((e, i) => i % 2 === 0);
Is there an easier, cleaner way to do this? I'd like to use a modern array method besides a for loop and push.
It's a good case for reduce. On even indexes, push the array from the input. On odd indexes, add the element to the last array...
const array = [['123 main street'], ['San Diego, CA, 92101'],['22 washington ave'],['Miami, FL, 56624']]
const addresses = array.reduce((acc, el, index) => {
return index % 2 ? acc[acc.length-1].push(el[0]) : acc.push(el), acc;
}, []);
console.log(addresses)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With