Search code examples
javascriptnestedternary

Nested ternary javascript


Having some trouble with a nested ternary:

Brief:

Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand.

Example input and output:

list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ])
// returns 'Bart, Lisa & Maggie'

list([ {name: 'Bart'}, {name: 'Lisa'} ])
// returns 'Bart & Lisa'

list([ {name: 'Bart'} ])
// returns 'Bart'

My JS:

var cache = '';
var data = [ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'}];
  for (i = 0 ; i < data.length; i++) {
    var people = data[i];

        cache += people.name + 
        (i==((length === 2) || (length === -1 )) ? ' & ' : // (if has two or is before last)
        (i==((length >= 3 ) || (length < 2)) ? ', ' : '') //not:(if has two or is before last) + >= 3 or < 2
        );
  }

THREE IS WORKING but not one or two


Solution

  • Here's my approach:

    function list(arr) {
      return arr.map(function(person) { return person.name; }) // Use only .name
      .join(", ") // Join with ", "
      .replace(/, (?!.*, )/, " & "); // Replace last ", " with " & "
    }