使用过滤器的Javascript数组比较函数-不工作

yi0zb3m4  于 2023-01-11  发布在  Java
关注(0)|答案(3)|浏览(165)

我写了下面的代码来回答这个问题:
编写一个函数justCoolStuff(),该函数接收两个字符串数组,并使用内置的.filter()方法返回一个数组,其中包含两个数组中都存在的项。
我想用循环而不是includes()数组方法来解决这个问题。我的思路对吗?代码返回一个用空数组填充的空数组。

const justCoolStuff = (arrOne,arrTwo) => {
  const sharedWord = [];
  for (i = 0; i < arrOne.length; i++) {
    for (j = 0; j < arrTwo.length; j++) {
      sharedWord.push(arrOne.filter(arr => arrOne[i] === arrTwo[j]));
    }
  }
  return sharedWord;
};

const coolStuff = ['gameboys', 'skateboards', 'backwards hats', 'fruit-by-the-foot', 'pogs', 'my room', 'temporary tattoos'];

const myStuff = [ 'rules', 'fruit-by-the-foot', 'wedgies', 'sweaters', 'skateboards', 'family-night', 'my room', 'braces', 'the information superhighway']; 

console.log(justCoolStuff(myStuff, coolStuff))

// Should print [ 'fruit-by-the-foot', 'skateboards', 'my room' ]

另外,有没有一种方法可以使用回调函数正确地编写它,使它更容易理解/阅读?

gmxoilav

gmxoilav1#

你的思路不对。

const justCoolStuff = (arrOne,arrTwo) => {
  //  const sharedWord = []; //you don't need this
  return arrOne.filter(function(item) {
    // you need to return true if item is in arrTwo
    // there are a number of ways in which you could test for this, one being
    // using includes on arrTwo
  });
};
7lrncoxx

7lrncoxx2#

下面的演示显示了如何使用**Array#filter**和Array#includes(或Array#indexOf):

const 
    coolStuff = ['gameboys', 'skateboards', 'backwards hats', 'fruit-by-the-foot', 'pogs', 'my room', 'temporary tattoos'],
    myStuff = [ 'rules', 'fruit-by-the-foot', 'wedgies', 'sweaters', 'skateboards', 'family-night', 'my room', 'braces', 'the information superhighway'],
    
    justCoolStuff = (arr1, arr2) => arr1.filter(item => arr2.includes(item)); //OR
    //justCoolStuff = (arr1, arr2) => arr1.filter(item => arr2.indexOf(item) > -1);
    
    console.log( justCoolStuff(coolStuff, myStuff) );
6yt4nkrj

6yt4nkrj3#

无阵列功能的解决方案

const justCoolStuff = (arrOne, arrTwo) => {
  const sharedWords = [];
  for (i = 0; i < arrOne.length; i++) {
    const item = arrOne[i]
    for (j = 0; j < arrTwo.length; j++) {
      const other = arrTwo[j]
      if (item === other) {
        sharedWords.push(item);
        break
      }
    }
  }
  return sharedWords;
};

const coolStuff = ['gameboys', 'skateboards', 'backwards hats', 'fruit-by-the-foot', 'pogs', 'my room', 'temporary tattoos'];

const myStuff = ['rules', 'fruit-by-the-foot', 'wedgies', 'sweaters', 'skateboards', 'family-night', 'my room', 'braces', 'the information superhighway'];

console.log(justCoolStuff(myStuff, coolStuff))

// Should print [ 'fruit-by-the-foot', 'skateboards', 'my room' ]

相关问题