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

前端 未结 16 931
终归单人心
终归单人心 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 10:10

    A few years later, here's a recursive generator solution. Enjoy!

    const intersperse = function *([first, ...rest], delim){
        yield first;
        if(!rest.length){
          return;
        }
        yield delim;
        yield * intersperse(rest, delim);
    };
    console.log([...intersperse(array, '&')]);
    
    0 讨论(0)
  • 2020-12-17 10:12

    ONE-LINER and FAST

    const intersperse = (ar,s)=>[...Array(2*ar.length-1)].map((_,i)=>i%2?s:ar[i/2]);
    
    console.log(intersperse([1, 2, 3], '&'));

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

    In ES6, you'd write a generator function that can produce an iterator which yields the input with the interspersed elements:

    function* intersperse(iterable, separator) {
        const iterator = iterable[Symbol.iterator]();
        const first = iterator.next();
        if (first.done) return;
        else yield first.value;
        for (const value of iterator) {
            yield separator;
            yield value;
        }
    }
    
    console.log(Array.from(intersperse([1, 2, 3], "&")));
    
    0 讨论(0)
  • 2020-12-17 10:16

    If you have Ramda in your dependencies or if willing to add it, there is intersperse method there.

    From the docs:

    Creates a new list with the separator interposed between elements.

    Dispatches to the intersperse method of the second argument, if present.

    R.intersperse('n', ['ba', 'a', 'a']); //=> ['ba', 'n', 'a', 'n', 'a']
    

    Or you can check out the source for one of the ways to do it in your codebase. https://github.com/ramda/ramda/blob/v0.24.1/src/intersperse.js

    0 讨论(0)
提交回复
热议问题