简单的方式来插入JavaScript数组中所有元素之间的元素? [英] Terse way to intersperse element between all elements in JavaScript array?

查看:124
本文介绍了简单的方式来插入JavaScript数组中所有元素之间的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个数组 var arr = [1,2,3] ,我想用元素分隔每个元素,例如。 var sep =&,所以输出是 [1,&,2,&,3] code>。



另一种想法的方法是我想做Array.prototype.join( arr.join(sep) ),而没有结果是一个字符串(因为我想要使用的元素和分隔符是对象,而不是字符串)。



是否有功能/漂亮/优雅的方式来做这个在es6 / 7或lodash没有任何感觉笨拙的东西像:

  _。 (arr.map((el,i)=> [el,i< arr.length-1?sep:null]))//太复杂

  _。flatten(arr.map(el => ; [el,sep])。slice(0,-1)// extra sep added,memory wasted 

甚至

  arr.reduce((prev,curr)=> {prev.push(curr,sep);返回上一个;},[])。slice(0,-1)
//可能是三个中最好的,但是我必须做一个地图已经
//,我还是一样问题如前两个 -
//内联三元或片

编辑:Haskell具有此功能,称为 intersperse

解决方案

使用生成器:

  function * intersperse(a,delim){
let first = true ;
for(const x of a){
if(!first)yield delim;
first = false;
yield x;
}
}

console.log([... intersperse(array,'&')]);

感谢@Bergi指出有用的泛化,输入可以是任何可迭代的。 >

如果你不喜欢使用生成器,那么<​​/ p>

  []。 (... a.map(e => ['&',e]))slice(1)


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, "&", 2, "&", 3].

Another way to think about it is I want to do Array.prototype.join (arr.join(sep)) without the result being a string (because the elements and separator I am trying to use are Objects, not strings).

Is there a functional/nice/elegant way to do this in either es6/7 or lodash without something that feels clunky like:

_.flatten(arr.map((el, i) => [el, i < arr.length-1 ? sep : null])) // too complex

or

_.flatten(arr.map(el => [el, sep]).slice(0,-1) // extra sep added, memory wasted

or even

arr.reduce((prev,curr) => { prev.push(curr, sep); return prev; }, []).slice(0,-1)
// probably the best out of the three, but I have to do a map already
// and I still have the same problem as the previous two - either
// inline ternary or slice

Edit: Haskell has this function, called intersperse

解决方案

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)

这篇关于简单的方式来插入JavaScript数组中所有元素之间的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆