Reputation: 1
Given the array below, I want to print the position (starting with 1) and the element item, for each element in the array in a single line.
let bag = ""
let arr = [1, 2, 3, "Ram", 2, "Chris"];
for (let i = 1; i < arr.length; i++) {
if (arr[i]) {
bag = bag + arr[i] + " ";
}
}
console.log(bag);
I want the log given to be similar to this, having position starting from 1 and the item of that element, for each element in a single line.
1: 1. 2: 2. 3: 3. 4: Ram. 5: 2. 6: Chris
Upvotes: 0
Views: 94
Reputation: 474
You can do that with two ways, the regular way with loops, and the advanced way with methods:
With Loops:
let bag = ""
let arr = [1, 2, 3, "Ram", 2, "Chris"]
for (let pos in arr) {
bag += pos + ": " + arr[pos]
if( pos != arr.length-1 ) bag += ". "
}
console.log(bag)
With Methods:
let arr = [1, 2, 3, "Ram", 2, "Chris"]
let result = arr.map((item, pos) => {
return `${pos}: ${item}${pos != arr.length-1 ? "." : ""}`
}).join(" ")
console.log( result )
Upvotes: 0
Reputation: 16728
The following solution makes use of the .map
and .join
methods on arrays:
let arr = [1, 2, 3, "Ram", 2, "Chris"];
console.log(arr.map(function(element, position) {
return `${position + 1}: ${element}`;
}).join(". "));
Upvotes: 2
Reputation: 27202
Try this :
let str = '';
const arr = [1, 2, 3, "Ram", 2, "Chris"];
for (let i = 1; i < arr.length; i++) {
str += (arr[i] && (i < arr.length - 1)) ? i + ': ' + arr[i] + ', ' : i + ': ' + arr[i]
}
console.log(str);
Upvotes: 0