3

This code works as intended based on the problem I am supposed to solve. However, as I am new to JavaScript, I was curious if this is the proper way to handle zipping two arrays. I've already read a few examples using map which seem concise, but I am more curious if there is a generally agreed upon proper method in JavaScript to do this?

var faker = require("faker");

var products = Array.from({length:10}, () => faker.commerce.productName());
var prices = Array.from({length:10}, () => faker.commerce.price())

var strOut = "";
for(var i=0; i<10; i++){
    strOut += `${products[i]} - ${prices[i]} \n`
}

console.log('====================\n'+
'WELCOME TO MY SHOP!\n'+
'====================\n'+
`${strOut}`);
1
  • 3
    You may have a reason for zipping, but the most common advice is "Don't use parallel arrays." A single array that contains objects such as { "product" : "some product", "price" : 5.99 } is a better structure. Commented Sep 28, 2018 at 0:20

1 Answer 1

3

1) reduce:

const strOut = products.reduce(
  (result, product, index) => `${result} ${product} ${prices[index]}\n`,
  ''
);

2) map + join:

const strOut = products.map( 
   (product, index) => `${product} ${prices[index]}`
).join("\n");

second argument of map's callback is the array index, you can use it for second array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.