[英]How to return null in Array.reduce()?
I have an array which could looks like this.我有一个看起来像这样的数组。 It's an array of dynamic length containing either a string or object.
它是一个包含字符串或 object 的动态长度数组。
['h', 'e', {apple: 2}, 'l', 'p']
I need to turn it into this:我需要把它变成这样:
[null, null, 'apple', 'apple', null, null]
So I was trying to use reduce
method and started with turning strings into null.所以我尝试使用
reduce
方法并开始将字符串转换为null。
.reduce(
(acc: Array<null | string>, val) => {
if (typeof val === "string") return acc.concat(null);
return acc.concat(val)
},
[]
);
it returns back:它返回:
[null]
and I expected:我期望:
[null, null, {apple: 2}, null, null]
Performance is moderately important, is it possible to do something like this with looping over array just once without resulting to for loops?性能相当重要,是否可以通过仅循环一次数组而不导致 for 循环来做这样的事情?
EDIT: sorry I made a stupid mistake, seems like my library turns it into ["he", {apple:3}, "lp"].编辑:对不起,我犯了一个愚蠢的错误,好像我的图书馆把它变成了 ["he", {apple:3}, "lp"]。
You can use Array.prototype.flatMap
-您可以使用
Array.prototype.flatMap
-
const process = (t = []) => t.flatMap ( v => Object(v) === v? Object.entries(v).flatMap(([ s, n ]) => Array(n).fill(s)): [ null ] ) const data = ['h', 'e', {apple: 2}, 'l', 'p'] const result = process(data) console.log(JSON.stringify(result)) // [null,null,"apple","apple",null,null]
If the object has multiple keys, each item will be expanded -如果 object 有多个键,每个项目将被扩展 -
const result =
process(['h', 'e', {apple: 2, pear: 3}, 'l', 'p', {berry: 1}])
console.log(JSON.stringify(result))
// [null,null,"apple","apple","pear","pear","pear",null,null,"berry"]
Array.prototype.flatMap
is just a specialised version of Array.prototype.reduce
- Array.prototype.flatMap
只是Array.prototype.reduce
的一个特殊版本 -
Array.prototype.flatMap = function (f, context)
{ return this.reduce
( (r, x) => r.concat(f.call(context, x))
, []
)
}
that?那?
const arr = ['h', 'e', {apple: 2}, 'l', 'p'] const rep = arr.reduce((a,c)=> { if (c instanceof Object) { let pair = Object.entries(c)[0] for (let n=0;n<pair[1];++n) a.push(pair[0]) } else a.push(null) return a },[]) console.log(...rep )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.