Sidath
Sidath

Reputation: 447

How to check if a value already exists in an array and remove that from array in react js?

I am creating an app with react js and it has a function to add data into an array. Now I need to check if a value already exists in an array. I have an array in state variable like this "Question: []". My array data like below and "QuesID","OpId","option" has different values.

[
{"QType":"Rating","QuesID":20,"OpId":1,"option":1},
{"QType":"Rating","QuesID":21,"OpId":1,"option":1},
]

if I send data {"QType":"Rating","QuesID":20,"OpId":2,"option":1} like this need to remove the previous value from an array and add this new value to an array.

This is what I tried,

addData= (event, item) => {
    var QType = "Rating";
    var QuesID = "22";
    var OpId = "1";
    var option = "1";
    
    var Qobj = { QType: QType, QuesID: QuesID, OpId: OpId, option: option };

    if (this.state.Question.find((item) => item.OpId === OpId) !== undefined) {
      console.log("item exist");
    } else {
      console.log("item not exist");
      this.state.Question.push(Qobj);
    }
    console.log(this.state.Question);
}

when it come data like this {"QType":"Rating","QuesID":20,"OpId":2,"option":1}, need to remove if it has a value with "QuesID"=20 and add the new value coming with "QuesID"=20. And also it will come data like below.

[{QType: "Rating", QuesID: "22", OpId: "4", option: "4"},
{QType: "Rating", QuesID: "23", OpId: "3", option: "3"},
{QType: "Rating", QuesID: "24", OpId: "2", option: "2"},
{QType: "Rating", QuesID: "25", OpId: "1", option: "1"}]

How can I fix this?

Full Code

    import React, { Component } from "react";
    import fullStarSrc from "../img/highlightedStar.png";
    import emptyStarSrc from "../img/star.png";
    
    export default class testPage extends Component {
      state = {
        qtemp2: [
          { idsurveyquestion: "22", question: "Taste of the food?" },
          { idsurveyquestion: "23", question: "Quality of the food?" },
          { idsurveyquestion: "24", question: "Speed Of delivery?" },
          { idsurveyquestion: "25", question: "The accuracy of the order?" },
          { idsurveyquestion: "26", question: "How is our service?" },
        ],
        Question: [],
      };
    
      rate = (event, item) => {
        const { id } = event.target;
        var i;
        console.log("You clicked: " + id);
    
        var QType = "Rating";
        var QuesID = id.substr(1, 2);
        var OpId = id.charAt(0);
        var option = id.charAt(0);
        console.log(QuesID);
    
var Qobj = { QType: QType, QuesID: QuesID, OpId: OpId, option: option };

    if (
      this.state.Question.find((item) => item.QuesID === QuesID) !== undefined
    ) {
      console.log("item exist");
    } else {
      console.log("Not exist item");
      this.state.Question.push(Qobj);
    }

    // this.state.Question.push(Qobj);
    console.log(this.state.Question);
    
        for (i = 1; i <= 5; i++) {
          if (parseInt(i + item.idsurveyquestion) <= parseInt(id)) {
            document
              .getElementById(parseInt(i + item.idsurveyquestion))
              .setAttribute("src", fullStarSrc);
          } else {
            document
              .getElementById(parseInt(i + item.idsurveyquestion))
              .setAttribute("src", emptyStarSrc);
          }
        }
      };
    
      render() {
        const { qtemp2 } = this.state;
        return (
          <div>
            <div class="bg">
              <div class="bg_img1"></div>
              <div class="heading1">
                <center>
                  <h2 class="head1">Please Rate Us</h2>
                </center>
              </div>
              <center>
                <div>
                  {qtemp2.map((item) => (
                    <>
                      <p key={item.idsurveyquestion}>{item.question}</p>
                      <div>
                        <img
                          onClick={(event) => this.rate(event, item)}
                          class="star"
                          id={"1" + item.idsurveyquestion}
                          src={emptyStarSrc}
                        />
                        <img
                          onClick={(event) => this.rate(event, item)}
                          class="star"
                          id={"2" + item.idsurveyquestion}
                          src={emptyStarSrc}
                        />
                        <img
                          onClick={(event) => this.rate(event, item)}
                          class="star"
                          id={"3" + item.idsurveyquestion}
                          src={emptyStarSrc}
                        />
                        <img
                          onClick={(event) => this.rate(event, item)}
                          class="star"
                          id={"4" + item.idsurveyquestion}
                          src={emptyStarSrc}
                        />
                        <img
                          onClick={(event) => this.rate(event, item)}
                          class="star"
                          id={"5" + item.idsurveyquestion}
                          src={emptyStarSrc}
                        />
                      </div>
                    </>
                  ))}
                </div>
              </center>
            </div>
          </div>
        );
      }
    }

And also I need to unselect the all-stars when clicking on the same star. How can I do it with a simple variable like adding "let toRemove = false;" and Where Should I add "toRemove = true;" ?

This is what I tried-> https://codesandbox.io/s/romantic-torvalds-j0995?file=/src/Rating2.js

Upvotes: 2

Views: 8632

Answers (5)

hannah
hannah

Reputation: 55

You simply use:

console.log(array.length)

Upvotes: 0

Mack
Mack

Reputation: 771

It looks like the QuesID property of your objects is being used as a key which uniquely identifies the question. For this reason, it could make more sense to store your data not as an array, but as an object where the data is indexed by it's QuesID. This lets you very easily access, delete or modify the data for a known QuesID. For example:

// state structured like this
{
  "22": {QType: "Rating", OpId: "4", option: "4"},
  "23": {QType: "Rating", OpId: "3", option: "3"},
  "24": {QType: "Rating", OpId: "2", option: "2"},
  "25": {QType: "Rating", OpId: "1", option: "1"}
}
addData = (event, item) => {
    var QType = "Rating";
    var QuesID = "22";
    var OpId = "1";
    var option = "1";
    
    var Qobj = { QType: QType, OpId: OpId, option: option };

    this.setState({
        Question: {
            ...this.state.Question,
            [QuesID]: Qobj
        }
    });
}

Upvotes: 0

Amruth
Amruth

Reputation: 5912

This login can help you.

  1. find index of the item
  2. then remove it
  3. update state.

->

let questions = this.state.Question;
  const index = questions.findIndex(item=>item.OpId === OpId);
  if(index > -1){
    questions.splice(index, 1);
    this.setState({Questions:arr})
  }

Upvotes: 0

Marco Nisi
Marco Nisi

Reputation: 1241

You need to do the following (replace your if else block with this):

 const index = this.state.Question.findIndex((item) => item.OpId === OpId)
 const newArray = [...this.state.Question]
 if (index !== -1) {
   console.log("item exist");
   newArray.splice(index, 1, item)
 } else {
   console.log("item not exist");
   newArray.push(Qobj);
 }
 this.setState({ Question: newArray })

Upvotes: 2

Abbasihsn
Abbasihsn

Reputation: 2171

first define some lists. one for checking Qtype and the other one for OpId, and etc:

let checkListQtype = [];
let checkListOpId = [];

then use this code:

let filteredData = YOURLIST.filter((item)=>{
if(checkListQtype.includes(item.QType) || checkListOpId.includes(item.OpId){
retrun false;
} else {
checkListQtype.push(item.QType);
checkListOpId.push(item.OpId);
return item;
}
});

Upvotes: 0

Related Questions