3

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.

2 Answers 2

7

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);

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

2 Comments

Dang it, not fast enough on my answer ;)
Ok cool, I wasn't super aware of the .map() function but that makes a lot of sense. Thanks for taking the time, off to read some MDN docs.
2

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

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

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.