20

I have an array with elements, for example array = ["example1", "example2", "example3"].

How can I print it in the following format?

  1. example1 2. example2 3. example 3...
0

12 Answers 12

23

Use forEach for this like below

var a = ["a", "b", "c"];
a.forEach(function(entry) {
  console.log(entry);
});

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

1 Comment

How does this even come close to answering the question? When run, it prints "a, "b", and "c" on separate lines. E.g., how does this print out the item numbers? Can you explain your answer, please? Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).
15

You can use a simple for loop:

for (i = 0; i < array.length; i++)
  document.writeln((i+1) + ": " + array[i]);

And use the document.writeln to print it out. See the below working snippet.

Snippet

array = ["example1", "example2", "example3"];
for (i = 0; i < array.length; i++)
  document.writeln((i+1) + ": " + array[i]);

Note: The document.writeln() is implemented differently many times. So you should use:

document.getElementById("id_of_div").innerHTML += (i+1) + ": " + array[i];

Comments

7

Instead of printing in a loop, I'd propose a simple functional transformation to generate a string that you can print (or use in another way):

var example = ["example1", "example2", "example3"]
var O = example.map( (e, i) => (i + 1 + "." + e) ).join(' ');
console.log(O);

It works by applying a .map() on your array, with an arrow function to combine each array element e and its index i into a string. You then just need to .join() the elements of the resulting array, using any separator you want (e.g. ' ').

3 Comments

Yes, explicit loops shouldn't be necessary for simple cases like this.
Will it scale? Or is there a Shlemiel the painter’s algorithm hidden in there (building a long string with short strings and reallocation & copy for every append)? Not a rhetorical question.
@PeterMortensen thanks for the edit - why shouldn't it scale: leanylabs.com/blog/js-forEach-map-reduce-vs-for-for_of
6

Use forEach for this like below(ES6)

var a = ["a", "b", "c"];
a.forEach((element) => {
        console.log(element)
    }
);

1 Comment

Like Vivek Kasture's answer, this doesn't answer the question.
2

You can use standard array methods to get the result you're after. MDN has some great documentation on array iteration methods.

var examples = ["example1", "example2", "example3"];

// You can use reduce to transform the array into result,
// appending the result of each element to the accumulated result.
var text = examples.reduce(function (result, item, index) {
    var item_number = index + 1;

    return result + " " + item_number + ". " + item;
}, "");

// You can use a variable with forEach to build up the
// result - similar to a for loop
var text = "";

examples.forEach(function (item, index) {
    var item_number = index + 1;

    text = text + " " + item_number + ". " + item;
});

// You can map each element to a new element which 
// contains the text you'd like, then join them
var text = examples.map(function (item, index) {
    var item_number = index + 1;
    return item_number + ". " + item;
}).join(" ");

// You can put them into an HTML element using document.getElementById
document.getElementById("example-text-result").innerHTML = text;

// or print them to the console (for node, or in your browser) 
// with console.log
console.log(text);

Comments

2

Try to use a for loop:

for (var i=0; i<array.length; i++)
    console.log(i + ". " + array[i]);

1 Comment

That outups in multiple strings.
1

You can try this:-

var arr = ['example1', 'example2', 'example3']
for (var i = 0; i < arr.length; i++){
    console.log((i + 1) + '. ' + arr[i])
}

Comments

1

You can do the following to print it out in one line:

let exampleArray = ["example1", "example2", "example3"];
let result = [];

 for (let i = 0; i < exampleArray.length; i++) {    
   result += i + 1 + ". " + exampleArray[i] + " ";
 }
 console.log(result);

Comments

1

Just my two cents:

let array = [
  [
    ['a', 'b', ['c', 13, ['d', 22, [44, [34]]]]],
    [1, 2, 3]
  ],
  [],
  [
    ['d', 'e', 'f', 'g', 'h'],
    [4, 5, 6, 7]
  ]
];

console.log(printArray(array));

function printArray(inputArr) {
  return "[" + _printArray(inputArr).intermediateVal + "]";
}

function _printArray(inputArr) {
  if (Array.isArray(inputArr)) {
    let str = "";
    for (let a = 0; a < inputArr.length; a++) {
      let result = _printArray(inputArr[a]);
      if (result.isComplexType) {
        str += "[" + result.intermediateVal + "]";
      } else {
        str += result.intermediateVal;
      }
      if (a + 1 < inputArr.length) {
        str += ", ";
      }
    }

    return {
      "isComplexType": true,
      "intermediateVal": str
    }
  } else {
    return {
      "isComplexType": false,
      "intermediateVal": inputArr
    }
  }
}

and prints this:

[[[a, b, [c, 13, [d, 22, [44, [34]]]]], [1, 2, 3]], [], [[d, e, f, g, h], [4, 5, 6, 7]]]

Comments

0

I was solving such a problem and I did this

const multiLanguages = ["C is fun", "Python is cool",  "JavaScript is amazing"];
for (let i = 0; i < multiLanguages.length; i++) {
  console.log(multiLanguages[i]);
}

Comments

0

If you want to do this in ES6 reduce will be good choice you over map. It declares predefined variable for you and event you don't need to join()

var array = ["example1", "example2", "example3"];
var op= array.reduce((ac,cur,ind)=> ac +` ${ind+1}.` + cur,'');
console.log(op);

With Map() and Join()

var array = ["example1", "example2", "example3"];
var op= array.map((e, i) =>`${i+1}.${e}`).join(' ');
console.log(op);

Comments

0

const arrayToString = (arr) => {
    return arr.join(" ");
};

const array = [2, 3, 4, 5, 6, 7, 8, 12, 34];
const result = arrayToString(array);
console.log(result);

Comments

Your Answer

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