[英]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),
[],
)
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.