Home > Back-end >  Javascript Add Element To Array At Specific Index and Remover "Join" Separator
Javascript Add Element To Array At Specific Index and Remover "Join" Separator

Time:10-06

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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