1

I am trying to create ONE string from an array of objects family and have them separated by commas except for the last element Mary

const family = [
{Person: {
name: John
}}, {Person: {
name: Mike
}}, {Person: {
name: Link
}}
, {Person: {
name: Mary
}}];

I want the string to be like this

"John, Mike, Link or Mary"

I tried using family.toString() but that gives me "John, Mike, Link, Mary" and doesn't allow me to replace "," with an "OR"

1
  • 2
    That's not a valid structure and is not an array. You posted an object with duplicate keys which can't exist Commented Apr 7, 2021 at 20:46

3 Answers 3

2

Use pop() to get (and remove) the last name. Then use join() to add the rest.

Thx to @charlietfl for suggesting a check on the number of names to prevent something like: and John.

const family = [
  { Person: { name: "John" } },
  { Person: { name: "Mike" } },
  { Person: { name: "Link" } },
  { Person: { name: "Mary" } }
];

// Get all the names
const names = family.map((x) => x.Person.name);

// Get result based on number of names
let result = '';
if (names.length === 1) {

    // Just show the single name
    result = names[0];
} else {
  
    // Get last name
    const lastName = names.pop();
    
    // Create result 
    result = names.join(', ') + ' and ' + lastName;
}
    
// Show output
console.log(result);

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

1 Comment

Might want to check array length is greater than one so you don't end up with just "and John"
0

I don't think there's a super-elogant option. Best bet is something like:

function joinWord(arr, sep, finalsep) {
    return arr.slice(0,-1).join(sep) + finalsep + arr[arr.length-1];
}

and then

joinWord(family.map(x=>x.person.name), ', ', ' or ');

You could make the invocation a little nicer at the cost of performance and modularity with:

Array.prototype.joinWord = function joinWord(sep, finalsep) {
    return this.slice(0,-1).join(sep) + finalsep + this[this.length-1];
}

family.map(x=>x.person.name).joinWord(', ', ' or ')

But this is only a good idea if this is going to come up a lot within your program and your program is never going to be a part of something bigger. It effects every array.

Comments

0

How about

let sp = ' or ';
family.map(x => x.Person.name)
  .reduceRight(
    (x,y) => {
      const r = sp + y + x;
      sp = ', ';
      return r;
}, '')
.replace(', ', '');

Hope, this question was for the school homework :)

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.