js比较数组中的元素使用(.map .filter .reduce)

时间:2019-12-26 20:01:16

标签: javascript arrays

我有两个数组,我需要比较该数组中的元素,并为每个元素返回带有计数器的数组。我需要使用“ .map”,“。filter”或“ .reduce”功能。谁能告诉我我该怎么做?或给我任何建议,我在哪里可以读到? (如何使用这三个函数(map,filter,reduce)将第一个数组的每个元素与第二个数组的每个元素进行比较?)

const fruits = [
  'apple', 
  'orange', 
  'papaya', 
  'apple', 
  'kiwi', 
  'orange', 
  'lime', 
  'kiwi', 
  'watermellon', 
  'kiwi', 
  'orange', 
  'fig',
];

const needs = [
  'apple',
  'orange',
  'watermellon',
];

const getFruits = (fruits) => {
  return fruits.map(fruit, needs) => (????)
 };

// I need this result:
//{
//  'apple': 2,
//  'orange': 3,
//  'watermellon': 1,
// };

3 个答案:

答案 0 :(得分:0)

有很多方法可以解决这个问题。一种方法是使用.map().filter()Object.fromEntries()

const fruits = [
  'apple', 
  'orange', 
  'papaya', 
  'apple', 
  'kiwi', 
  'orange', 
  'lime', 
  'kiwi', 
  'watermelon', 
  'kiwi', 
  'orange', 
  'fig',
];

const needs = [
  'apple',
  'orange',
  'watermelon',
];

const getFruits = (f, n) => {
   //Object.fromEntries() is used to convert the array into an object.
   return Object.fromEntries(n.map(v => 
     //v is the key, the value is how many of v there is
     [v, f.filter(val => val === v).length]
   ));
};
console.log(getFruits(fruits, needs));

我为您拼写了watermelon。 ?

答案 1 :(得分:0)

您可以过滤数据并通过计算值来减少过滤后的数组。

const
    fruits = ['apple', 'orange', 'papaya', 'apple', 'kiwi', 'orange', 'lime', 'kiwi', 'watermelon', 'kiwi', 'orange', 'fig'],
    needs = ['apple', 'orange', 'watermelon'],
    result = fruits
        .filter(value => needs.includes(value))
        .reduce((counts, value) => {
            counts[value] = (counts[value] || 0) + 1;
            return counts;
        }, {});

console.log(result);

答案 2 :(得分:0)

const fruits = [
  'apple', 
  'orange', 
  'papaya', 
  'apple', 
  'kiwi', 
  'orange', 
  'lime', 
  'kiwi', 
  'watermelon', 
  'kiwi', 
  'orange', 
  'fig',
];

const needs = [
  'apple',
  'orange',
  'watermelon',
];

let counter = {};

needs.map(i=>counter[i]=0);

fruits.map(fruit => {
  if(Object.keys(counter).includes(fruit)){ 
	counter[fruit] +=1;
  }
});
 
console.log(counter);