2

The below code shows the array of duplicate data's , But I need a Unique data's from the array. I tried many steps, but I can't find the solution:

See the below image of the output of duplicate received

See the Image of duplicate data's

JS File

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>
    );}}

Thanks in Advance..!!

10
  • 3
    Does this answer your question? Get all unique values in a JavaScript array (remove duplicates) Commented Nov 30, 2019 at 7:13
  • 3
    You can use a Set: this.setState({datas: [...new Set(responseData.data)]}) Commented Nov 30, 2019 at 7:13
  • I tried many steps - such as? Commented Nov 30, 2019 at 7:19
  • 2
    provide a sample data format that you receive and also post what you have tried Commented Nov 30, 2019 at 7:23
  • @Bravo are words, not code? Commented Nov 30, 2019 at 8:59

1 Answer 1

5

There's many ways to remove duplicates from array, Use Sets to remove your duplicates.

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: [] });
 }
Sign up to request clarification or add additional context in comments.

1 Comment

which one is the array item.category or responseData.data?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.