0

I need to know how I can split an array with commas and if it's the last one element to the last one I have , and and if it's the last one I add . to it. I have the following code. The output as one big string honda, audi, tesla, and toyota. the following is printing more than one. Also what if I wanted to push it one time into new array. So one big array of string ["honda, audi, tesla, and toyota."]

let namesArray = ["honda", "audi", "tesla", "toyota"];
let newOrder = ""
namesArray.forEach((item, index) => {
  console.log(index);

  if (index === namesArray.length - 2) {
    newOrder = item + ' , and'
  } else if (index === namesArray.length - 1) {
    newOrder = (item + '.')
  } else {
    newOrder = (item + ',')
  }

})
console.log('new string ', newOrder)

"new string ", "honda,audi,tesla,toyota."

4
  • Add "and " and "." to the last element, then use arr.join(", ") Commented May 18, 2021 at 22:42
  • 1
    To fix your existing code you need to append to your existing string, not reassign, so use newOrder += item + .... Commented May 18, 2021 at 22:43
  • @HereticMonkey when i do newOrder.append(item + ' , and') I get Uncaught TypeError: newOrder.append is not a function Commented May 18, 2021 at 22:47
  • 3
    ... Right. Look at my comment again. I didn't say "use newOrder.append. I said use newOrder += instead of newOrder =. Commented May 18, 2021 at 22:49

3 Answers 3

4

In terms of what is wrong with your existing code, you are not adding the new string value to your output (i.e. use newOrder +=, not newOrder = in the loop):

let namesArray = ["honda", "audi", "tesla", "toyota"];
let newOrder = ""
namesArray.forEach((item, index) => {
  if (index === namesArray.length - 2) {
    newOrder += item + ', and '
  } else if (index === namesArray.length - 1) {
    newOrder += (item + '.')
  } else {
    newOrder += (item + ', ')
  }

})
console.log(newOrder)

It would be simpler though to just join a slice of the array from the start to the second to last element, then add , and and the last element to that string:

let namesArray=["honda", "audi", "tesla", "toyota"];

let newOrder = namesArray.slice(0,-1).join(', ') + ', and ' + namesArray.slice(-1) + '.';

console.log(newOrder)

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

5 Comments

what am I doing wrong. like what if I dont use slice and join. how come my for loop is not doing it
@blex it will work as long as the array has 2 or more elements, in this case it would produce honda, and audi.
in slice is -1 the last element?
OP should look at that as an index. 0 index starts just before 0.... -1 index is just before the last element. Indexes are always in front of their Array position.
@Metawaa negative numbers refer to "an offset from the end of the sequence". Since start is inclusive and end is exclusive, slice(-1) includes elements starting from the last element, while slice(0,-1) slices from the first element to the element before the last element.
2

You can easily achieve this result using map and join

const arr = ["honda", "audi", "tesla", "toyota"];

const result = arr
  .map((item, index) => {
    if (index === arr.length - 1) {
      return `and ${item}.`;
    } else {
      return `${item}, `;
    }
  })
  .join("");
console.log(result);

You can also use string template literal if the array size in known prior

const arr = ["honda", "audi", "tesla", "toyota"];
const [a, b, c, d] = arr;
const result = `${a}, ${b}, ${c}, and ${d}.`;
console.log(result);

Comments

0

I would create a function for reuse. First make a .slice() of your array, so the original is not affected. .pop() off the last Array element. Then .join(', ') and concatenate +', and ' along with the element you popped off +'.'.

function andIt(array){
  const a = array.slice(), p = a.pop()+'.';
  if(!a.length){
    return p;
  }
  return a.join(', ')+', and '+p;
}
const namesArray = ['honda', 'audi', 'tesla', 'toyota'];
console.log(andIt(namesArray)); console.log(andIt(['test']));

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.