最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Conditional array.join in Javascript - Stack Overflow

programmeradmin1浏览0评论

I have an array of strings and I would like to display them as a comma separated string but add "and" for the last element. For example I have

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.join(' ,'); 

outputs

'Banana, Orange, Apple, Mango'

Is there any way the I add "and" for the last word so it outputs

'Banana, Orange, Apple and Mango'

I have an array of strings and I would like to display them as a comma separated string but add "and" for the last element. For example I have

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.join(' ,'); 

outputs

'Banana, Orange, Apple, Mango'

Is there any way the I add "and" for the last word so it outputs

'Banana, Orange, Apple and Mango'
Share Improve this question asked Oct 30, 2016 at 12:18 snowflakes74snowflakes74 1,3071 gold badge20 silver badges48 bronze badges 1
  • You can use .reduce or replace the last comma in the string. – VLAZ Commented Oct 30, 2016 at 12:24
Add a comment  | 

5 Answers 5

Reset to default 9

You may instead use Array.reduce function and implement your own logic, for example:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.reduce(function (p, d, i) {
  return p + (i === fruits.length - 1 ? ' and ' : ', ') + d;
});

You can join the first 3 elements of the array using slice and join then append the last element concatenated with 'and'.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.slice(0, fruits.length - 1).join(', '); 
energy += ' and ' + fruits[fruits.length - 1];

You can't pass a function to .join, unfortunately, so you do need to iterate through the loop and join it yourself:

const array = ['banana', 'apple', 'taco']

let result = array[0]
for (let i = 1; i < array.length; i++) {
  if (i < array.length - 1) {
    result += ', ' + array[i]
  } else {
    result += ' and ' + array[i]
  }
}

console.log(result)

You could make a function for this, though:

// General purpose custom/dynamic join function creator.
function dynamicJoin(fn) {
  return function(array) {
    let result = array[0]
    for (let i = 1; i < array.length; i++) {
      const joiner = fn(array[i - 1], array[i], i, array)
      result += joiner + array[i]
    }
    return result
  }
}

const joinCommaOrAnd = dynamicJoin(function(a, b, i, arr) {
  return (i === arr.length - 1) ? ' and ' : ', '
})

console.log(joinCommaOrAnd(['bread', 'fish', 'butter']))

Function toSentence of underscore.string has the exact functionality you want. If you don't want to get whole library, you could just borrow toSentence:

function toSentence(array, separator, lastSeparator, serial) {
  separator = separator || ', ';
  lastSeparator = lastSeparator || ' and ';
  var a = array.slice(),
    lastMember = a.pop();

  if (array.length > 2 && serial) lastSeparator = separator + lastSeparator;

  return a.length ? a.join(separator) + lastSeparator + lastMember : lastMember;
};

You can try this,

var delimiter = ', ';
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.join(delimiter); 
var index = energy.lastIndexOf(delimiter);
energy = energy.substring(0, index) + ' and ' + energy.substring(index + delimiter.length);

console.log(energy);

发布评论

评论列表(0)

  1. 暂无评论