Di Nerd Apps
Di Nerd Apps

Reputation: 818

Create One string from elements in an Array of Objects

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"

Upvotes: 1

Views: 1308

Answers (3)

0stone0
0stone0

Reputation: 43964

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

Upvotes: 2

DraganS
DraganS

Reputation: 2699

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 :)

Upvotes: 0

dspeyer
dspeyer

Reputation: 3036

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.

Upvotes: 0

Related Questions