[英]Javascript - Workaround for flatmap
So I was looking for some workaround for flat map as it doesn't work on IE and I find this one: But I don't really understand why does it work所以我一直在寻找一些平面 map 的解决方法,因为它在 IE 上不起作用,我找到了这个:但我真的不明白为什么它会起作用
var gadjets = [
{computers:['asus', 'hp'],
sellphones:['Galaxy', 'Nokia']
},
{computers:['dell', 'insys'],
sellphones:['iphone', 'samsung']
}
];
const getValues = gadjets.reduce((acc, gadjet) => acc.concat(gadjet[computers]), []) // instead of gadjets.flatMap(gadjet=> gadjet[computers])
This code returns:此代码返回:
['asus','hp','dell','insys']
But shouldn't it return:但它不应该返回:
['asus','hp'],['dell', 'insys']
This is because reduce
adds up the elements you give it.这是因为
reduce
将你给它的元素加起来。 For example, take the following code:例如,采用以下代码:
let arr = [1,2,3,4,5];
console.log(arr.reduce((before, value)=>before+value));
This code takes each value
and adds it to before
.此代码获取每个
value
并将其添加到before
。 It then passes that added value into the next iteration of reduce
, in the before
variable.然后它将添加的值传递给
reduce
的下一次迭代,在before
变量中。
In your code, you were passing an array into before
, or in your case acc
, and concatenates (merge) a new array from gadgets['computers']
and returns that array.在您的代码中,您将一个数组传递给
before
,或者在您的情况下为acc
,并从gadgets['computers']
连接(合并)一个新数组并返回该数组。 This creates a list of the computers from the array of objects.这将根据对象数组创建计算机列表。
In case you want the output to be array of arrays.如果您希望 output 成为 arrays 的数组。 Try this:
尝试这个:
var gadjets = [ { computers: ["asus", "hp"], sellphones: ["Galaxy", "Nokia"] }, { computers: ["dell", "insys"], sellphones: ["iphone", "samsung"] } ]; const groupBy = key => { let res = gadjets.reduce((objectsByKeyValue, obj) => { let arr = []; arr.push(obj[key]); return objectsByKeyValue.concat(arr); }, []); return res; }; console.log(groupBy("computers"));
But shouldn't it return
但它不应该返回吗
I'm not sure what you're trying to show us there, but if you mean我不确定你想在那里向我们展示什么,但如果你的意思是
[['asus','hp'],['dell', 'insys']]
then no, it shouldn't.那么不,不应该。
concat
flattens arrays you pass it (to a single level): concat
将 arrays 展平,您将其传递(到单个级别):
const a = [].concat(['asus','hp'], ['dell', 'insys']); console.log(a); // ["asus", "hp", "dell", "insys"]
So acc.concat(gadjet[computers])
flattens out each of those computers
arrays into a new array, which is the accumulation result of the reduce
.因此
acc.concat(gadjet[computers])
将每台computers
arrays 展平为一个新数组,这是reduce
的累加结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.