Terse way to intersperse element between all elements in JavaScript array?

前端 未结 16 930
终归单人心
终归单人心 2020-12-17 09:19

Say I have an array var arr = [1, 2, 3], and I want to separate each element by an element eg. var sep = \"&\", so the output is [1, \"&a

相关标签:
16条回答
  • 2020-12-17 09:58

    you can also use the following:

    var arr =['a', 'b', 'c', 'd'];
    arr.forEach(function(element, index, array){
        array.splice(2*index+1, 0, '&');
    });
    arr.pop();
    
    0 讨论(0)
  • 2020-12-17 10:00

    Updated for objects not using join method:

    for (var i=0;i<arr.length;i++;) {
        newarr.push(arr[i]);
        if(i>0) { 
          newarr.push('&'); 
         }    
    }
    

    newarr should be:

    newarr = ['a','&','b','&','c','&','d']; 
    
    0 讨论(0)
  • 2020-12-17 10:02

    const arr = [1, 2, 3];
    
    function intersperse(items, separator) {
      const result = items.reduce(
        (res, el) => [...res, el, separator], []);
      result.pop();
      return result;
    }
    
    console.log(intersperse(arr, '&'));

    0 讨论(0)
  • 2020-12-17 10:06

    Using reduce but without slice

    var arr = ['a','b','c','d'];
    var lastIndex = arr.length-1;
    arr.reduce((res,x,index)=>{
       res.push(x);
       if(lastIndex !== index)
        res.push('&');
      return res;
    },[]);
    
    0 讨论(0)
  • 2020-12-17 10:06

    My take:

    const _ = require('lodash');
    
    _.mixin({
        intersperse(array, sep) {
            return _(array)
                .flatMap(x => [x, sep])
                .take(2 * array.length - 1)
                .value();
        },
    });
    
    // _.intersperse(["a", "b", "c"], "-")
    // > ["a", "-", "b", "-", "c"]
    
    0 讨论(0)
  • 2020-12-17 10:10

    Using a generator:

    function *intersperse(a, delim) {
      let first = true;
      for (const x of a) {
        if (!first) yield delim;
        first = false;
        yield x;
      }
    }
    
    console.log([...intersperse(array, '&')]);
    

    Thanks to @Bergi for pointing out the useful generalization that the input could be any iterable.

    If you don't like using generators, then

    [].concat(...a.map(e => ['&', e])).slice(1)
    
    0 讨论(0)
提交回复
热议问题