Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

javascript - How to sort array of repeated object keys day values and create a new array with object coordinates where y will hold the value of repetitions

Iterating the dates array to create a new array with the following format

 const dates= [
          {datetime:'Monday'},
          {datetime:'Tuesday'},
          {datetime:'Wednesday'},
          {datetime:'Thursday'},
          {datetime:'Monday'},
          {datetime:'Wednesday'},
          {datetime:'Friday'},
          {datetime:'Monday'}]
        // Result 
   result = [ { x: 'Monday', y: 3 },
   { x: 'Tuesday', y: 1 },
   { x: 'Wednesday', y: 2 },
   { x: 'Thursday', y: 1 },
   { x: 'Friday', y: 1 } ]

question from:https://stackoverflow.com/questions/65623382/how-to-sort-array-of-repeated-object-keys-day-values-and-create-a-new-array-with

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could group and count by date then transform it to array of your expectation with map

const dates = [
  { datetime: "Monday" },
  { datetime: "Tuesday" },
  { datetime: "Wednesday" },
  { datetime: "Thursday" },
  { datetime: "Monday" },
  { datetime: "Wednesday" },
  { datetime: "Friday" },
  { datetime: "Monday" },
];

const groupByDatetime = dates.reduce((acc, el) => {
  acc[el.datetime] = (acc[el.datetime] || 0) + 1;
  return acc;
}, {});

const res = Object.entries(groupByDatetime).map(([datetime, count]) => ({
  x: datetime,
  y: count,
}));

console.log(res);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...