简体   繁体   English

通过其他子数组的值获取子数组

[英]Get subarray by value of other subarray

I have next object: 我有下一个对象:

u = {date:[1,2,2,1,5,6,2,8], uid:[11,22,33,44,55,66,77,88]}

And i want to get the array of values from 'uid' subarray by 'date' subarray. 我想通过'date'子数组从'uid'子数组中获取值的数组。 Like this: give me uids where date is '1'. 像这样:给我提供日期为“ 1”的uid。 Result: [11, 44]. 结果:[11,44]。

How? 怎么样?

You can use reduce to loop thru the date array. 您可以使用reduce循环遍历日期数组。 Check if the value is the same with the date, concat the u.uid[i] to the accumulator. 检查值是与日期相同, concatu.uid[i]到蓄能器。

 var u = { date: [1, 2, 2, 1, 5, 6, 2, 8], uid: [11, 22, 33, 44, 55, 66, 77, 88] } var date = 1; var result = u.date.reduce((c, v, i) => v === date ? c.concat(u.uid[i]) : c, []); console.log(result); 

You can use a combination of map (transforming each date element to its corresponding uid element if it matches your target date) and filter (to only keep "interesting" results in the final array): 您可以使用map (如果每个date元素与目标日期匹配,则将每个date元素转换为其对应的uid元素)和filter (仅将“有趣的”结果保留在最终数组中)的组合:

 var u = { date: [1, 2, 2, 1, 5, 6, 2, 8], uid: [11, 22, 33, 44, 55, 66, 77, 88] }; function getUid(date) { return u.date.map((d, i) => d === date ? u.uid[i] : false) .filter(v => v); } console.log(getUid(1)); console.log(getUid(5)); 

You could reduce the date array by taking the corresponding uid value at the same index if the date is the wanted date. 如果日期是所需日期,则可以通过在相同的索引处获取相应的uid值来减少日期数组。

 function getUID(date) { return u.date.reduce( (r, d, i) => d === date ? r.concat(u.uid[i]) : r, [] ); } var u = { date: [1, 2, 2, 1, 5, 6, 2, 8], uid: [11, 22, 33, 44, 55, 66, 77, 88] }; console.log(getUID(1)); 

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM