0
var fruits = ["Apple", "Banana","Pineapple"];
console.log(fruits[0])
console.log(fruits[1])
console.log(fruits[2])

So I've created an array here which contains the name of 3 fruits. I'm able to log each element in the array using its index number in a separate line but I'm wondering if there's a way I can do this in just 1 line.

Thank you

EDIT: Sorry I didn't make it clear because my example logged all elements. But I want it so that I simply choose which wants I want to log. So I have an array with the 3 fruits but in one line I just want to log the first and last entry.

3
  • console.log(fruits.split(' ')); ? Commented Dec 5, 2015 at 14:18
  • console.dir(fruits) will make it possible to examine the whole array in the console. Commented Dec 5, 2015 at 14:19
  • console.log(fruits) works too. Commented Dec 5, 2015 at 14:20

3 Answers 3

2

join() is what you're looking for. The default separator is a comma so console.log(fruits.join()) will give you

Apple,Banana,Pineapple

The join() method takes a string, so console.log(fruits.join('|')) will give you

Apple|Banana|Pineapple

while console.log(fruits.join(' and ')) will give you

Apple and Banana and Pineapple

The Mozilla Developer Network JavaScript reference is an excellent resource, though of course you first need to know what to look up. Here's the MDN entry for Array.prototype.join()

EDIT: You changed the question while I was answering. To log specific items,

console.log([fruits[0],fruits[2]].join(' and '))

yields

Apple and Pineapple

If you don't mind adding a library to the mix you'll find some excellent helper functions in lodash. The function _.at() might be useful for what you're trying to do (note that join() is unnecessary if you're fine with ', ' as the separator):

console.log(_.at(fruits, [0, 2]))

gives you

Apple, Pineapple

You don't need to put the indices in an array, so console.log(_.at(fruits, 1, 2)) yields

Banana, Pineapple

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

1 Comment

Correct me if I'm wrong but all this does is just allow me to log the array without the [] and my own choice of separator. What I want is the ability to log any combination of arrays in a single line. For example, the way I first tried to do what I wanted was using console.log(fruits[0, 2]) but that doesn't work.
2

The following will call console.log for each fruit, so you will see one fruit per line:

fruits.forEach(function(fruit){ console.log(fruit) });

The following will call console.log only once with the fruits as the arguments, so you will see all fruits in the same line:

console.log.apply(console, fruits);

Comments

0

So you mean you want to log "Apple Pineapple"? If so then this will do the trick:

console.log(fruits[0]+" "+fruits[fruits.length-1])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.