简体   繁体   English

类似于Java中的Array.prototype.join的地图或平面图

[英]Map or flatmap that works like Array.prototype.join in Javascript

I find the functionality of Array.prototype.join very useful because it only applies the join value to the "inner" connections of the elements in the array. 我发现Array.prototype.join的功能非常有用,因为它仅将联接值应用于数组元素的“内部”连接。 Like so: 像这样:

['Hey', 'there'].join('-') // Hey-there

Where Array.protoype.map produces a 'leftover' dash in this example: 在此示例中, Array.protoype.map产生“剩余”破折号:

['Hey', 'there'].map(value => value + '-') // Hey-there-

I've been looking for a succinct way to map arrays without converting them to a string, possibly to a new array, like so: 我一直在寻找一种简洁的方式来映射数组,而不将其转换为字符串,可能转换为新数组,如下所示:

// Intended behaviour ['Hey', 'there'].mapJoin('-') // ['Hey', '-', 'there']

I'm NOT looking for an imperative solution to the problem as I could write that myself and put it in a global import somewhere. 我并不是在寻找一种当务之急的解决方案,因为我可以自己写一个,然后将其放在全局中。 I'm looking for a native way (ES6 is fine) to express it elegantly so I can write it in all my projects. 我正在寻找一种本机表达方式(ES6很好)来优雅地表达它,以便可以在我的所有项目中编写它。

You could join with a wanted separator, and split by the addition comma (or any other value, if taken for join). 您可以使用所需的分隔符进行连接,并用加号逗号分隔(或其他任何值,如果用于连接)。

 var array = ['Hey', 'there'], separator = '-', result = array.join(',' + separator + ',').split(','); console.log(result); 

Another solution could be to take new indices and fill the previos index with the sepparator. 另一个解决方案是采用新索引,并用分隔符填充previos索引。

 var array = ['Hey', 'there'], separator = '-', result = Object.assign( [], ...array.map((v, i) => ({ [i * 2 - 1]: separator, [i * 2]: v })) ); console.log(result); 

You're looking for Ramda's intersperse . 您正在寻找Ramda的穿插物

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

Though it's implemented imperatively. 尽管必须执行

It's not exactly pretty or elegant, but 它不完全漂亮或优雅,但是

['Hey', 'there'].reduce(
  (acc, value, i, arr) => (acc.push(value), i < arr.length - 1 ? acc.push('-') : 0, acc),
  [],
)

Alternate version of @ AKX 's answer. @ AKX答案的替代版本。

 const data = ['Hey', 'there']; const output = data.reduce((p, c, i, a) => p.concat(i < a.length -1 ? [c, '-'] : [c]), []); console.log(output) 

You can try this one 你可以试试这个

 const mapJoin = (arr, joiner) => { return arr.reduce( (curr, t) => curr.concat(t, joiner), []).slice(0, arr.length*2-1) } const data = ["Hey", "There"] console.log(mapJoin(data, "-")) 

A simple recursive encoding 一个简单的递归编码

 const intersperse = (sep, [ x, ...rest ]) => // base case; return empty result x === undefined ? [] // one remaining x, return singleton : rest.length === 0 ? [ x ] // default case; return pair of x and sep and recur : [ x, sep ] .concat (intersperse (sep, rest)) console.log ( intersperse ("~", []) // [] , intersperse ("~", [ 1 ]) // [ 1 ] , intersperse ("~", [ 1, 2 ]) // [ 1, ~, 2 ] , intersperse ("~", [ 1, 2, 3 ]) // [ 1, ~, 2, ~, 3 ] , intersperse ("~", [ 1, 2, 3, 4 ]) // [ 1, ~, 2, ~, 3, ~, 4 ] ) 

You're looking for the intersperse function, which is easy to define: 您正在寻找易于定义的intersperse函数:

 const intersperse = (x, ys) => [].concat(...ys.map(y => [x, y])).slice(1); console.log(intersperse("-", ["Hey", "there"])); // ["Hey", "-", "there"] console.log(intersperse(0, [1, 2, 3])); // [1, 0, 2, 0, 3] console.log(intersperse(0, [])); // [] 

Alternatively, you could decompose it into smaller functions: 或者,您可以将其分解为较小的函数:

 const concat = xss => [].concat(...xss); const concatMap = (f, xs) => concat(xs.map(f)); const intersperse = (x, ys) => concatMap(y => [x, y], ys).slice(1); console.log(intersperse("-", ["Hey", "there"])); // ["Hey", "-", "there"] console.log(intersperse(0, [1, 2, 3])); // [1, 0, 2, 0, 3] console.log(intersperse(0, [])); // [] 

You can even install them on Array.prototype : 您甚至可以将它们安装在Array.prototype

 Object.assign(Array.prototype, { concatenate() { return [].concat(...this); }, concatMap(f) { return this.map(f).concatenate(); }, intersperse(x) { return this.concatMap(y => [x, y]).slice(1); } }); console.log(["Hey", "there"].intersperse("-")); // ["Hey", "-", "there"] console.log([1, 2, 3].intersperse(0)); // [1, 0, 2, 0, 3] console.log([].intersperse(0)); // [] 

In Haskell, you'd write this as follows: 在Haskell中,您可以这样编写:

intersperse :: a -> [a] -> [a]
intersperse x = drop 1 . concatMap (\y -> [x, y])

Can you see the similarities? 您能看到相似之处吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Javascript中,Array.join真的是Array.prototype.join吗? - In Javascript, is Array.join really Array.prototype.join? Array.prototype.join在IE 8中不起作用 - Array.prototype.join not working in IE 8 如何在reactjs中使用array.prototype.join - How to using array.prototype.join in reactjs 为什么 Array.prototype.map 会忽略稀疏数组中的空槽,而 Array.prototype.join 不会? - Why does Array.prototype.map ignore empty slots in a sparse array whereas Array.prototype.join does not? 为什么 Array.prototype.join() 会展平任意深度的数组? - Why does Array.prototype.join() flatten an array of any depth? 我怎样才能真正理解&#39;Array.prototype.join&#39;的方法 - How can I really understand the method of 'Array.prototype.join' Array.prototype.join() 在反应 useState 中不起作用 - Array.prototype.join() doesn't work in react useState 除了Array.prototype.join()以外,还有没有更短的方法将数组连接到一个字符串? - Is there a shorter way to join an array to one string besides Array.prototype.join()? 我尝试编写自己的Array.prototype.join()有什么问题? - What's wrong with my attempt to write my own Array.prototype.join()? 为什么javascript中没有Array.prototype.flatMap? - Why no Array.prototype.flatMap in javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM