0
votes

Is it possible to make an array from my reduce result?

For Example this code

const fruitBasket = ['banana', 'cherry', 'orange', 'apple', 'cherry', 'orange', 'apple', 'banana', 'cherry', 'orange', 'fig'];

const count = fruitBasket.reduce((tally, fruit) => {
  tally[fruit] = (tally[fruit] || 0) + 1;
  return tally;
}, {})

console.log(count) // { banana: 2, cherry: 3, orange: 3, apple: 2, fig: 1 }

Can I get an array from count?

Something like

const NewArrayName = [
 {fruit: "banana", num: "2"},
 {fruit: "orange", num: "3"}
 ]; ```

3
{"orange" : "2", "banana" : "3"} is not an arrayCertainPerformance
Object or Array ?dnaz
["orange" : "2", "banana" : "3"] is not a valid syntax. Please create a minimal reproducible exampleadiga

3 Answers

1
votes

You can create an object with a key values in reduce method and then use Object.values() to get desired result:

const fruitBasket = ['banana', 'cherry', 'orange', 'apple', 'cherry', 'orange', 
    'apple', 'banana', 'cherry', 'orange', 'fig'];

const count = fruitBasket.reduce((acc, fruit) => {
  acc.values[fruit] = (acc.values[fruit] || 0) + 1;
  return acc;
}, {values: {}})

const output = Object.values(count)
console.log(`An array: `, output) 
console.log(`An object: `, ...output) 

UPDATE:

To get "banana" and "2":

let banana = output[0]['banana'];
0
votes

change your initial value from an obj to an array and it will be an array. Then you can get the count by tally. ${"fruit name here"} by calling it on the count as a callback maybe.

const fruitBasket = ['banana', 'cherry', 'orange', 'apple', 'cherry', 'orange', 'apple', 'banana', 'cherry', 'orange', 'fig'];

const count = fruitBasket.reduce((tally, fruit) => {
  tally[fruit] = (tally[fruit] || 0) + 1;
  return tally;
}, [])

console.log(count) // [ banana: 2, cherry: 3, orange: 3, apple: 2, fig: 1 ]
0
votes

Here's how you can get your desired output in an array of objects-

const fruitBasket = ['fig', 'banana', 'cherry', 'orange', 'apple', 'cherry', 'orange', 'apple', 'banana', 'cherry', 'orange', 'fig', 'pineapple'];




const fruitObj = fruitBasket.reduce((acc, fruit) => {


  if (!acc.length) {

    acc.push({ 'fruit': fruit, 'count': 1 });

  } else {


    let i = 0;

    while (i < acc.length) {

      if (acc[i]['fruit'] !== fruit && i === acc.length - 1) {
        acc.push({ 'fruit': fruit, 'count': 1 });
        break;

      } else if (acc[i]['fruit'] === fruit) {
        ++acc[i]['count'];
        break;
      }
      i++;

    }
  }
  return acc;

}, []);

console.log(fruitObj);