需要将两个数组与一个回调进行比较并以Javascript返回一个对象

问题描述 投票:1回答:3

构造一个函数objOfMatches,它接受两个数组和一个回调。 objOfMatches将建立一个对象并返回它。为了构建对象,objOfMatches将使用回调测试第一个数组的每个元素,以查看输出是否匹配第二个数组的相应元素(按索引)。如果存在匹配项,则第一个数组中的元素将成为对象中的键,而第二个数组中的元素将成为对应的值。到目前为止,我知道了:

const objOfMatches = (arr1,arr2,call) => {
let result = {};
for(let i = 0; i < arr1.length; i++){
 //Don't know how to check each element using the callback
}
return result
}


const arr1 = ['hi', 'howdy', 'bye', 'later', 'hello'];
const arr2 = ['HI', 'Howdy', 'BYE', 'later', 'HELLO'];
function uppercaser(str) { return str.toUpperCase(); }
console.log(objOfMatches(arr1, arr2, uppercaser)); 
// should log: { hi: 'HI', bye: 'BYE', hello: 'HELLO' }
javascript
3个回答
2
投票

尝试一下:

const objOfMatches = (arr1,arr2,call) => {
     let result = {};
     for(let i = 0; i < arr1.length; i++){
          let upper = call(arr1[i]);
          if(arr2[i] && upper == arr2[i])
               result[arr1[i]] = arr2[i];
     }
     return result
}
const arr1 = ['hi', 'howdy', 'bye', 'later', 'hello'];
const arr2 = ['HI', 'Howdy', 'BYE', 'later', 'HELLO'];
function uppercaser(str) { return str.toUpperCase(); }
console.log(objOfMatches(arr1, arr2, uppercaser));

0
投票

const objOfMatches = (arr1,arr2,call) => {
  let result = {};
  for(let i = 0; i < arr1.length; i++){
     if(call(arr1[i]) === arr2[i]) {
      result[arr1[i]] = arr2[i]
     }
  }
  return result;
}


const arr1 = ['hi', 'howdy', 'bye', 'later', 'hello'];
const arr2 = ['HI', 'Howdy', 'BYE', 'later', 'HELLO'];
function uppercaser(str) { return str.toUpperCase(); }
console.log(objOfMatches(arr1, arr2, uppercaser)); 
// should log: { hi: 'HI', bye: 'BYE', hello: 'HELLO' }

0
投票

这里是一个功能编程解决方案:

const objOfMatches = (arr1, arr2, call) => 
    Object.fromEntries(arr1
        .map((v,i) => [v, arr2[i]])
        .filter(([a,b]) => call(a) === b)
    );


const arr1 = ['hi', 'howdy', 'bye', 'later', 'hello'];
const arr2 = ['HI', 'Howdy', 'BYE', 'later', 'HELLO'];
const uppercaser = str => str.toUpperCase();
console.log(objOfMatches(arr1, arr2, uppercaser)); 
© www.soinside.com 2019 - 2024. All rights reserved.