0

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

3
  • 3
    What is it in your code that you expect to prepend the numeric values to each array element? Commented Dec 17, 2018 at 16:22
  • Nothing in your code indicates a number... Commented Dec 17, 2018 at 16:23
  • array.map(function(e, i){return (i+1) + '.' + e}).join() Commented Dec 17, 2018 at 16:23

4 Answers 4

1

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));

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

1 Comment

Hey, just a quick question for me to better understand. Why did you put join outside of else statement? Is there a specific reason?
1

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);

Comments

0

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([]));

Comments

0

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);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.