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. Like this: give me uids where date is '1'. Result: [11, 44].
How?
You can use reduce
to loop thru the date array. Check if the value is the same with the date, concat
the u.uid[i]
to the accumulator.
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):
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.
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.