1

I have a ReactJS page with three dropdown list, two of the dropdown list are displaying duplicate values. The values are being consumed from a json file. I researched using filter to remove the duplicates, but I'm unsure as to how I'm to apply it to my array when using React JS along with Fetch. I created a function which employs the filter method, but I'm uncertain as to how I'm to implement it onto data: [], which contains the data consumed from the json file. This is the sample json file: https://api.myjson.com/bins/b1i6q

This is my code:

import React, { Component } from "react";

class Ast extends Component {
  constructor() {
    super();
    this.state = {
      data: [],
      cfmRateFactor: "10"
    };
  } //end constructor

  change = e => {
    this.setState({
      [e.target.name]: e.target.value
    });
  }; //end change

     removeDups(array) {
    return array.reduce((result, elem) => {
        if (!result.some((e) => e.clientName === elem.clientName)) {
            result.push(elem);
        }
        return result;
    } , []);
}

  componentWillMount() {
    fetch("https://api.myjson.com/bins/b1i6q", {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-type": "application/json"
      }
      /*body: JSON.stringify({
            username: '{userName}',
            password: '{password}'
        })*/
    }) /*end fetch */
      .then(results => results.json())
      .then(data => this.setState({ data: data }));
  } //end life cycle

  render() {
    console.log(this.state.data);
    return (
      <div>
        <div className="container">
          <div className="astContainer">
            <form>
              <div>
                <h2>Memeber Selection:</h2>

                {["clientName", "siteName", "segmentName"].map(key => (
                  <div className="dropdown-padding">
                    <select key={key} className="custom-select">
                      {this.state.data.map(({ [key]: value }) => (
                        <option key={value}>{value}</option>
                      ))}
                    </select>
                  </div>
                ))}
              </div>

              <div className="txt_cfm">
                <label for="example-text-input">Modify CFM Rate Factor:</label>
                <input
                  class="form-control"
                  type="textbox"
                  id="cfmRateFactor"
                  name="cfmRateFactor"
                  value={this.state.cfmRateFactor}
                  onChange={e => this.change(e)}
                />
              </div>
              <div>
                <div>
                  <button type="submit" className="btn btn-primary">
                    Submit
                  </button>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    );
  }
}

export default Ast;

Could I please get some help with this? I'm still very new to using React JS.

2 Answers 2

1

You could use Map, it's a data structure for keeping key-value pairs. It will give you best performance for large data.

removeDuplicates(arr) {
  const map = new Map();
  arr.forEach(v => map.set(v.abc_buildingid, v)) // having `abc_buildingid` is always unique
  return [...map.values()];
}


// this hook is better to start fetching data than componentWillMount
componentDidMount() {
    fetch("https://api.myjson.com/bins/b1i6q", {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-type": "application/json"
      }
    })
    .then(results => results.json())
    .then(data => this.setState({ data: this.removeDuplicates(data) })); // use the defined method
} //end life cycle
Sign up to request clarification or add additional context in comments.

1 Comment

@user1724708 :)
0

filter won't solve your problem. But reduce will.

You could have the following :

function removeDups(array) {
    return array.reduce((result, elem) => {
        if (!result.some((e) => e.abc_buildingid === element.abc_buildingid)) {
            result.push(elem);
        }
        return result;
    } , []);
}

1 Comment

I modified my code (see above) the dropdown clientName is what's displaying duplicates. Well, when used on the actual production json file, both clientName and segmentName dropdowns show duplicates; I applied the modification, but the duplicates still appear. What am I doing wrong? thanks in advance

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.