javascript - 如何在 native react 中从数组中删除重复项

标签 javascript arrays reactjs react-native

下面的代码显示了重复数据的数组,但我需要数组中的唯一数据。 我尝试了很多步骤,但找不到解决方案:

请参阅下图所示的重复接收的输出

See the Image of duplicate data's

JS 文件

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      storage: [],

    };
    this.renderData = this.renderData.bind(this);
  }
  renderData({ item, index }) {
  const datas = Array.from(new Set(item.category)); 
    return (
      <View>
        <Text>{datas}</Text>
      </View>
    );
  }
  componentDidMount() {
    fetch('http://myjsonpage', {
      method: 'post',
      headers: { 
        Accept: 'application/json',
        'Content-Type': 'application/json',},
      body: JSON.stringify({
        token: 'XXXXXX',
      }),
    }).then(response => { response.json().then(responseData => {
        if (responseData.status === 1) {
            this.setState({ datas:responseData.data}) ;
        } else {
          this.setState({ storage: [] });
        }
      });});}
  render() {
    return (
      <View style={styles.continer}>
        <View style={styles.heading}>
          <Text style={styles.font}> Most Common Categories </Text>
        </View>
        <View style={styles.item}>
          <FlatList data={this.state.datas} renderItem={this.renderData} />
        </View>
      </View>
    );}}

提前致谢..!!

最佳答案

有很多方法可以从数组中删除重复项,使用Sets删除重复项。

const data = ['Renewal', 'Subscriptions', 'Subscriptions', 'Subscriptions', 'Renewal', 'Renewal']

const unique = new Set(data);

const uniqueData = [...unique]; // array

const data = ['Renewal', 'Subscriptions', 'Subscriptions', 'Subscriptions', 'Renewal', 'Renewal']

const uniqueData = [...new Set(data)];

console.log(uniqueData);

if (responseData.status === 1) {
   this.setState({ datas: [...new Set(responseData.data)] }) ;
 } else {
   this.setState({ storage: [] });
 }

关于javascript - 如何在 native react 中从数组中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59114027/

相关文章:

javascript - 取消选中复选框后如何在文本框不消失的情况下清除文本框(JavaScript)

javascript - 使用python获取firefox保存的cookie

c++ - 将原始数据包装在 std 容器中,如数组,具有运行时大小

javascript - React/Redux - 调度方法 - 返回错误

arrays - 更新状态数组中的一个值 react 原生

javascript - src/app/app-routing.module.ts(10,11) : error TS1005: ',' expected 中的错误

python - 如何在 Tkinter 中将二维数组从一个类传递到另一个类?

java - 为什么要求我为这个面试任务返回一个数组?

javascript - 转换日期格式

javascript - 由于未知原因,我的随机播放功能在 26 处停止。我怎样才能让它洗所有的牌呢?