Anthony
Anthony

Reputation: 388

Populating an array using a for loop and another array

This is more a learning exercise and nothing super critical - I'm unsure of the best way to Google what I'm looking for, I clicked through a few others suggested answers and didn't find anything that looked super relevant.

I'm wondering if there's a way I can populate an array using another array and a for loop (as opposed to modifying the contents of the existing array in place). What I envision is something like:

var existingArray = ["Thing1", "Thing2", "Thing3"];

let newArray = for (var i=0; i < existingArray.length; i++) {
  "Modified string " + existingArray[i];
}

// Output: ["Modified string Thing1", "Modified string Thing2", "Modified string Thing3"]

where I can just create the new array variable and populate it more or less in the same block of code. I know how to do it the maybe more traditional way where I just say:

newArray = [];
oldArray = ["Thing1", "Thing2", "Thing3"]

for (var i = 0; i < oldArray.length; i++) {
  newArray.push("Modified string " + oldArray[i]);
}

I'm sorry if this is a somewhat stupid question, I'm just curious if there's a way to do this and if there's any advantage to doing so. It seems like it would be cool to just declare a new array and populate it all with one little chunk of code instead of declaring the new array, then using .push() to populate it.

Upvotes: 3

Views: 895

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370779

It would be even better to use .map, since you're transforming one array into another, only one line required:

const existingArray = ["Thing1", "Thing2", "Thing3"];
console.log(
  existingArray.map(thing => 'Modified string ' + thing)
);

When you don't have an existing array to .map from, you can still do something similar to create an array immediately by using Array.from - define the length in the first argument, and put the map function in the second argument:

const originalArray = Array.from({ length: 3 }, (_, i) => 'Thing ' + (i + 1));
console.log(originalArray);

Upvotes: 7

Piotr Mirosz
Piotr Mirosz

Reputation: 866

newArray = [];
oldArray = ["Thing1", "Thing2", "Thing3"]

for (i in oldArray) {
  newArray.push("Modified string " + oldArray[i]);
}
console.log(newArray)

Upvotes: 2

Related Questions