JavaScript 匹配两个数组
javascriptweb developmentobject oriented programming
假设我们有两个数组,一个是字符串文字,另一个是对象。
const data = [{ name: 'Kamlesh Kapasi', uid: 123 }, { name: 'Mahesh Babu', uid: 129 }, { name: 'Akshay Kapoor', uid: 223 }, { name: 'Vikas Gupta', uid: 423 }, { name: 'Mohit Dalal', uid: 133 }, { name: 'Rajkumar Hirani', uid: 233 }, { name: 'Joy', uid: 127 }]; const names = ['Joy', 'Rajkumar Hirani', 'Akshay Kapoor', 'Mahesh Babu', 'Mohit Dalal', 'Kamlesh Kapasi', 'Vikas Gupta']
我们的工作是编写一个函数,迭代 names 数组并构造一个数字数组,该数组包含特定名称的 uid,其顺序与 names 数组中出现的顺序相同。
让我们来编写该函数的代码 −
示例
const data = [{ name: 'Kamlesh Kapasi', uid: 123 }, { name: 'Mahesh Babu', uid: 129 }, { name: 'Akshay Kapoor', uid: 223 }, { name: 'Vikas Gupta', uid: 423 }, { name: 'Mohit Dalal', uid: 133 }, { name: 'Rajkumar Hirani', uid: 233 }, { name: 'Joy', uid: 127 }]; const names = ['Joy', 'Rajkumar Hirani', 'Akshay Kapoor', 'Mahesh Babu', 'Mohit Dalal', 'Kamlesh Kapasi', 'Vikas Gupta'] const mapId = (arr, names) => { return names.reduce((acc, val) => { const index = arr.findIndex(el => el.name === val); return acc.concat(arr[index].uid); }, []); } console.log(mapId(data, names));
输出
控制台中的输出将是 −
[ 127, 233, 223, 129, 133, 123, 423 ]