Home > front end >  How to count repeating value inside an array of object
How to count repeating value inside an array of object

Time:09-26

const vehicle = [
  {
    a: [
      {
        vehicle_name: "Toyota",
        color: "black"
      },
      {
        vehicle_name: "Toyota",
        color: "red"
      },
      {
        vehicle_name: "Ford",
        color: "yellow"
      },
      {
        vehicle_name: "Toyota",
        color: "white"
      }
    ]
  },
  {
    b: [
      {
        vehicle_name: "Honda",
        color: "black"
      },
      {
        vehicle_name: "Honda",
        color: "red"
      },
      {
        vehicle_name: "Ford",
        color: "yellow"
      },
      {
        vehicle_name: "Toyota",
        color: "white"
      }
    ]
  }
]

Given the array of obj above, My goal is to get the total number of vehicle in each key. Note: if the vehicle_name is repeated it should only count as 1. Expected Output:

const result = [
  {
    a: {
      count: 2
    }
  },
  {
    b: {
      count: 3
    }
  }
]

Explanation: The count of key a => is 2 because although it have 4 vehicles but Toyota is repeated so it only count as 1. Same goes in key b => the count is 3 because it has three different name(Honda, Ford, Toyota)

CodePudding user response:

You can use map to iterate the objects in vehicle, then Object.entries to iterate those objects, using reduce to count the unique vehicles seen in the objects in each array value:

const vehicle = [
  {
  a: [
    { vehicle_name: "Toyota", color: "black" },
    { vehicle_name: "Toyota", color: "red" },
    { vehicle_name: "Ford", color: "yellow" },
    { vehicle_name: "Toyota", color: "white" }
  ]
  },
  {
  b: [
    { vehicle_name: "Honda", color: "black" },
    { vehicle_name: "Honda", color: "red" },
    { vehicle_name: "Ford", color: "yellow" },
    { vehicle_name: "Toyota", color: "white" }
    ]
  }
]

const result =
  vehicle.map(o => Object.fromEntries(
    Object.entries(o).map(([k, a]) => [k, { count : 
      a.reduce((acc, { vehicle_name }) => {
        if (!(vehicle_name in acc)) {
          acc[vehicle_name] = 1
          acc.count  
        }
        return acc
      }, { count: 0 }).count }
    ])
  )
)

console.log(result)

  • Related