Reuse a JS function

1

Hello with the following line of code, how do I modify it and print the amount of each type of fruit using the same function?

var fruits = ["Banana", "Orange", "Apple", "Mango","Orange", "Orange", 
"Apple", "Mango"];

var cant = fruits.filter(function(value) {
    return value == "Orange";
})

console.log(cant.length);
    
asked by Rafael Pereira 30.07.2018 в 21:29
source

4 answers

1

You can create a function that accepts an Array and an x element to search, and returns the number of elements x found equal

var fruits = ["Banana", "Orange", "Apple", "Mango","Orange", "Orange", 
"Apple", "Mango"];

function myFunction(myArr, xelement ) {
    return (myArr.filter(x => x == xelement )).length;
}


console.log(myFunction(fruits,"Orange"));
    
answered by 30.07.2018 / 21:55
source
1

There are other ways to count the number of times an element repeats itself within an array, but using your code you can do the following by iterating each element and checking if the array has already been filtered by that element.

var fruits = ["Banana", "Orange", "Apple", "Mango", "Orange", "Orange", "Apple", "Mango"
];

var counted = [];

fruits.forEach(function(element) {
  if (!counted.includes(element)) {
    var cant = fruits.filter(function(value) {
      return value == element;
    }).length;
    counted.push(element);
    console.log(element + " = " + cant);
  }
});
    
answered by 30.07.2018 в 21:51
1

Something simple could be using encapsulating your filter

const frutas = ["Banana", "Orange", "Apple", "Mango","Orange"];

const contarFrutas = (valor, listaDeFrutas) => (
  listaDeFrutas.filter(fruta => fruta === valor).length
); 

console.log(
 contarFrutas('Banana', frutas)
);

console.log(
 contarFrutas('Orange', frutas)
);
    
answered by 30.07.2018 в 21:56
1

var a = ["Banana", "Orange", "Apple", "Mango","Orange"].reduce(function (array, index) {

  array[index] ? array[index]++ : array[index] = 1
  return array;
}, {});

console.log(a)
    
answered by 31.07.2018 в 00:50