Search code examples
javascriptarraysobjectreduce

creating the the count of the each array number


const users = [
  { f: "aks", l: "shaini", age: 26 },
  { f: "donald", l: "trump", age: 75 },
  { f: "elon", l: "musk", age: 50 },
  { f: "deepika", l: "padukone", age: 26 },
];

const output = users.reduce((acc, curr) => {
  if (acc[curr.age]) {
    acc[curr.age] = ++acc[curr.age];
  } else { 
    acc[curr.age] = 1;
  }
  return acc;
}, {});
console.log(output);

output for this code i : {26: 2, 50: 1, 75: 1}

function findOdd(A) {
 
  if (A.length === 1) return A[0];
  const output = A.reduce((acc, curr) => {
    if (acc[curr]) {
      acc[curr] = ++acc[curr];
    } else {
      acc[curr] = 1;
    }
  }, {});
  return output;
}

console.log(findOdd([20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5]));

and this code gives an error

index.js:21 Uncaught TypeError: Cannot read properties of undefined (reading '1')
    at index.js:21:12
    at Array.reduce (<anonymous>)
    at findOdd (index.js:20:20)
    at index.js:30:13

I am practicing the reduce function and it works fine when I am taking num from an object property and it is not working with the array containing numbers

can anyone help me , what's wrong in this code ?


Solution

  • Your code can be corrected and reduced to:

    const users = [
      { f: "aks", l: "shaini", age: 26 },
      { f: "donald", l: "trump", age: 75 },
      { f: "elon", l: "musk", age: 50 },
      { f: "deepika", l: "padukone", age: 26 },
    ];
    
    const output = users.reduce((acc, {age}) => ({...acc,[age]:(acc[age] || 0) + 1}), {});
    console.log(output);

    function findOdd(A) {
      return A.reduce((acc, curr) => ({...acc,[curr]:(acc[curr] || 0) + 1}), {});
    }
    
    //OR const findOdd = A => A.reduce((acc, curr) => ({...acc,[curr]:(acc[curr] || 0) + 1}), {});
    
    console.log(findOdd([20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5]));