使用React JS计算字符串数组中的重复项 [英] Count the duplicates in a string array using React JS

查看:101
本文介绍了使用React JS计算字符串数组中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我实现的代码,用于在React应用程序中使用Chart js创建条形图.它在此处创建一个条形图,其中所有数据都位于一个数组中.但是,我只想更改此代码,以便在x轴(目标,y轴)中提供输出.因为它有许多重复的目的地,所以该目的地的出现次数不计其数.我搜索了此方法,但找不到正确的解决方案.谁能帮我做到这一点?

Following is a code I implemented to create a bar chart using chart js in React app. Here it creates a bar chart with all the data in an array. But, I want to change this code only to give the output in the x-axis - destination, y-axis - no. of occurrence of this destination since it has many repeated destinations. I searched methods to this but I couldn't get a correct solution. Can anyone help me to do this?

const dataArrayY4 = [];
res.data.map(item => {
  dataArrayY4.push(item.time)
})
const dataArrayX4 = []
res.data.map(item => {
  dataArrayX4.push(item.destination)
})
this.setState({
  data4: dataArrayY4,
  labels4: dataArrayX4,
});

推荐答案

这可以按照以下步骤进行:

This could be done as follows:

const res = {
  data: [
    { time: 1, destination: 'A'},
    { time: 3, destination: 'A'},
    { time: 2, destination: 'B'}    
  ]
};

let tmp4 = [];
res.data.map((o, i) => {
  const existing = tmp4.find(e => e.destination == o.destination);
  if (existing) {
    existing.time += o.time;
  } else {
    tmp4.push({time: o.time, destination: o.destination});
  }
})

this.setState({
  data4: tmp.map(o => o.time);
  labels4: tmp.map(o => o.destination);
});

可以使用 Array.reduce() 而不是 Array.map() .

Above code could further be optimized by using Array.reduce() instead of Array.map().

这篇关于使用React JS计算字符串数组中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆