Reputation: 3
var array = ['a', 'b', 'c']
function arrayTransform(array) {
if (array.lengths === 0) {
console.log("Empty")
} else {
console.log(array.join());
}
}
arrayTransform(array);
the outcome should be 1.a, 2.b, 3.c I am getting abc
Upvotes: 0
Views: 70
Reputation: 2867
Welcome to Stackoverflow. Would you mind using the ES6 solution as shared below. Let me know if you need it in ES5.
let result = array.map((val, i) => i + 1 + "." + val);
console.log(result);
Upvotes: 0
Reputation: 39322
You can use .reduce()
to get the resultant string:
let data = ['a', 'b', 'c'];
let reducer = arr => arr.length ?
arr.reduce((r, c, i) => (r.push(`${i + 1}.${c}`), r), []).join() :
'Empty';
console.log(reducer(data));
console.log(reducer([]));
Upvotes: 0
Reputation: 50291
Seems you wnat to add the index with the element. In that case use map
function which will return an array and then use join
to create the final string
var array = ['a', 'b', 'c']
function arrayTransform(array) {
if (array.lengths === 0) {
console.log("Empty")
} else {
return array.map((item, index) => {
return `${index+1}.${item}` // template literals
}).join()
}
}
console.log(arrayTransform(array));
Upvotes: 1
Reputation: 386560
You could map the incremented index with the value and join it to the wanted style.
var array = ['a', 'b', 'c']
function arrayTransform(array) {
if (array.lengths === 0) {
console.log("Empty")
} else {
console.log(array.map((v, i) => [i + 1, v].join('.')).join());
}
}
arrayTransform(array);
Upvotes: 1