基于公共键将两个 Javascript 数组组合成一个结果数组,类似于SQL中的JOIN操作。
const innerJoin = (xs, ys, sel) => xs.reduce((zs, x) => ys.reduce((zs, y) => // cartesian product - all combinations zs.concat(sel(x, y) || []), // filter out the rows and columns you want zs), []);
const userProfiles = [ {id: 1, name: "Ashok"}, {id: 2, name: "Amit"}, {id: 3, name: "Rajeev"}, ]; const questions = [ {id: 1, text: "text1", createdBy: 2}, {id: 2, text: "text2", createdBy: 2}, {id: 3, text: "text3", createdBy: 1}, {id: 4, text: "text4", createdBy: 2}, {id: 5, text: "text5", createdBy: 3}, {id: 6, text: "text6", createdBy: 3}, ];
const result = innerJoin(userProfiles, questions, ({id: uid, name}, {id, text, createdBy}) => createdBy === uid && {id, text, name});
Open your browser console to see the output. [ { id: 1, text: 'text3', name: 'Ashok' }, { id: 2, text: 'text1', name: 'Amit' }, { id: 2, text: 'text2', name: 'Amit' }, { id: 4, text: 'text4', name: 'Amit' }, { id: 5, text: 'text5', name: 'Rajeev' }, { id: 6, text: 'text6', name: 'Rajeev' } ]
以上是如何在 Javascript 数组上执行内连接?的详细内容。更多信息请关注PHP中文网其他相关文章!