1

I have an array of arrays. I want to merge the first item from each array within the array. How could I go about that?

Here's my array:

var array = [["plums", "peaches", "pineapples"], ["carrots", "corn", "green beans"], ["chocolate", "ice cream"]];

I want the output to be:

var newArray = ["plums", "carrots", "chocolate"];

This is what I tried:

<!doctype html>
<html>
<body>
<script>
  var array = [["plums", "peaches", "pineapples"], ["carrots", "corn", "green beans"], ["chocolate", "ice cream"]];

  var arrLength = array.length;
  var newArray = [];

  for (var i = 0; i < arrLength; i++) {
newArray = [].concat.apply([], array[i][0]);
  };
  console.log("new merged array:", newArray);

</script>
</body>
</html>

However, in the console, I get this error:

CreateListFromArrayLike called on non-object.

How can I accomplish this?

1 Answer 1

2

You can use Array.prototype.map(). Read more here.

var array = [["plums", "peaches", "pineapples"], ["carrots", "corn", "green beans"], ["chocolate", "ice cream"]];
var newArray = array.map(x => x[0])

However, if you want to use a for loop to iterate the elements, you can do,

var newArray = []
for (let i = 0; i < array.length; i++) {
    // Since you want the first element,
    newArray.push(array[i][0])
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is awesome. So concise. Thanks!

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.