Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

216
Vistas
Javascript Add Element To Array At Specific Index and Remover "Join" Separator

I'm aware this question has been asked many times but I can't find the solution to my specific problem. I'm guessing that I need to refactor my code entirely but could use some guidance.

I am practicing OOP in Javascript. I would like to join an array and add an "and" conjunction before the last element. That way [1, 2, 3] ==> "1, 2, and 3".

I have included my code with comments below. As you will see, the current output I'm getting is "1, 2, and, 3". How can I get rid of the extra comma? Am I going about this the wrong way?

class Person {
  constructor(first, last, age, gender, interests) {
    this.name = {
      first: first,
      last: last,
    };
    this.age = age;
    this.gender = gender;
    this.interests = interests;
  }

  greeting() {
    console.log(`Hi! I'm ${this.name.first} ${this.name.last}.`)
  }

  bio() {
    // store the index of the last element of the array in a variable called index
    let index = this.interests.length - 1;
    // store the conjunction for end of array
    let conjunction = " and"
    // insert the conjunction before last element in array
    this.interests.splice(index, 0, conjunction)
    // join the array into a string separated by commas
    let interestsString = this.interests.join(", ");
    console.log(interestsString);
  }
}

let person1 = new Person('test', 'test', '29', 'Male', ['skiing', 'cooking', 'gardening']);

console.log(person1.bio());

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Use Intl.ListFormat() to convert the list to a string while handling the separator, and the conjunction:

const listFormatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });

class Person {
  constructor(first, last, age, gender, interests) {
    this.name = {
      first: first,
      last: last,
    };
    this.age = age;
    this.gender = gender;
    this.interests = interests;
  }

  greeting() {
    console.log(`Hi! I'm ${this.name.first} ${this.name.last}.`)
  }

  bio() {
    return listFormatter.format(this.interests);
  }
}

let person1 = new Person('test', 'test', '29', 'Male', ['skiing', 'cooking', 'gardening']);

console.log(person1.bio());

Another option is to use array manipulation - if the array contains only a single item, return that item. If the it contains more than one item, create a new array with all the original items, but the last, and the last item back after adding "and" to it. Join the array.

class Person {
  constructor(first, last, age, gender, interests) {
    this.name = {
      first: first,
      last: last,
    };
    this.age = age;
    this.gender = gender;
    this.interests = interests;
  }

  greeting() {
    console.log(`Hi! I'm ${this.name.first} ${this.name.last}.`)
  }

  bio() {
    return this.interests.length > 1 // if there are multiple items
      ?
      [
        ...this.interests.slice(0, -1), // get all items but the last
        `and ${this.interests.at(-1)}` // add the last item with "and"
      ].join(', ') // join
      :
      this.interests.at(0); // just take the single existing item
  }
}

let person1 = new Person('test', 'test', '29', 'Male', ['skiing', 'cooking', 'gardening']);

console.log(person1.bio());

about 4 years ago · Juan Pablo Isaza Denunciar

0

Here's one way of doing what you need.

class Person {
  constructor(first, last, age, gender, interests) {
    this.name = {
      first: first,
      last: last,
    };
    this.age = age;
    this.gender = gender;
    this.interests = interests;
  }

  greeting() {
    console.log(`Hi! I'm ${this.name.first} ${this.name.last}.`)
  }

  bio() {
    let interestsString = this.interests.join(', ').replace(/, ([^,]*)$/, ' and $1')
    console.log(interestsString);
  }
}

let person1 = new Person('test', 'test', '29', 'Male', ['skiing', 'cooking', 'gardening']);

console.log(person1.bio());

about 4 years ago · Juan Pablo Isaza Denunciar

0

when you used splice like this

 this.interests.splice(index, 0, conjunction)

you add element to the array , then the join function added another "," better to just change the element it self and adding the and to it.

like this:

    let changeTo = conjunction + this.interests[index];
    this.interests.splice(index, 1, changeTo);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda