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
CodePudding user response:
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(". "));
CodePudding user response:
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);
CodePudding user response:
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 )