Is there a way to push a string onto the end of each element in the array(I have to use the while loop?

Viewed 332

Create a function johnLennonFacts.

This function will accept one argument, an array of facts about John Lennon (note that it might not be exactly the following facts):

const facts = [
  "He was the last Beatle to learn to drive",
  "He was never a vegetarian",
  "He was a choir boy and boy scout",
  "He hated the sound of his own voice"
];

Use a while loop to loop over the facts array and add "!!!" to the end of every fact. Return an array of strings with exclamation points.

function johnLennonFacts(array) {

    let i = 0;
    while (i < (0, array.length, i++)) {
        array.push('!!!');
    }
    return array;
}

I keep returning the original array but I need to add the explanation points to them through the while loop.

3 Answers

You need concatenation not push, i.e push adds a new element to array whereas your desired output needs to add ( concatenate ) !!! at the end of element so use string concatenation

const facts = [
  "He was the last Beatle to learn to drive",
  "He was never a vegetarian",
  "He was a choir boy and boy scout",
  "He hated the sound of his own voice"
];

const final = facts.map(e=> e + '!!!')

console.log(final)

Your original code can be changed to

function johnLennonFacts(array) {
  let i = 0;
  let newArray = []
  while (i < array.length) {
    newArray.push(array[i] + ' !!!')
    i++
  }
  return newArray;
}

const facts = [
  "He was the last Beatle to learn to drive",
  "He was never a vegetarian",
  "He was a choir boy and boy scout",
  "He hated the sound of his own voice"
];

console.log(johnLennonFacts(facts))

You're attempting to add new elements to the array when you use push(). You need to modify the existing elements' string values.

const facts = [
  "He was the last Beatle to learn to drive",
  "He was never a vegetarian",
  "He was a choir boy and boy scout",
  "He hated the sound of his own voice"
];

function makeFactsExciting(array) {
  var i;

  for (i = 0; i < array.length; i++) {
    array[i] = array[i] + '!!!';
  }

  return array;
}

console.log( makeFactsExciting(facts) );

You can use forEach to modify the original array if you do not want to create a new array i.e. what happens when you use map():

const facts = [
  "He was the last Beatle to learn to drive",
  "He was never a vegetarian",
  "He was a choir boy and boy scout",
  "He hated the sound of his own voice"
];

facts.forEach((v, i) => facts[i] = `${v}!!!`);

console.log(facts);

Related