Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compare last 2 elements in an array

I want to compare elements in an array. The values of the array is getting from selecting the checkbox in a grid.I want to compare last 2 selected element’s data in the array. For example my array is like on first selection
let arr = [{aID:5, name: "trt", address:"tyuy", type:"ttype"}].
That time there is no need of comparison. On second checkbox selection

arr=[{aID:5, name: "trt", address:"tyuy", type:"ttype"},
{aID:6, name: "trt", address:"thyr", type:"ttype"},
]

compare 2 elements type and name be same, my code is like,

for (let i = 0; i < selected.length; i++) {
      for (let k = i + 1; k < selected.length; k++) {
          if ((selected[i].type === selected[k].type) &&(selected[i].name === selected[k].name)) {
            this.setState({ selectedRowKeys: e, selectedRecords: selected })
          }
          else{
            return message.warning("Select lien with same type and Name.")
          }
      }
      if(selected.length === 1){
      this.setState({ selectedRowKeys: e, selectedRecords: selected })
      }

This code works perfectly on 2 selection but the isssue is starts from 3rd selection on third selction we selct different type and name row it also given checked as I per my code. I want to compare last 2 elements like,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let arr =[{aID:5, name: "trt", address:"tyuy", type:"ttype"},
{aID:6, name: "trt", address:"thyr", type:"ttype"},
{aID:6, name: "gdg", address:"thyr", type:"ptype"},
] 

expected result is not show the selection of the checkbox of different type and name and also show the warning.

>Solution :

let arr=[{aID:5, name: "trt", address:"tyuy", type:"ttype"},
  {aID:6, name: "trt", address:"thyr", type:"ttype"},
  ]

  if(arr.length > 1){
    if(arr[arr.length-1].type === arr[arr.length-2].type && arr[arr.length-1].name === arr[arr.length-2].name){
        //code if true
    }else{

    }
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading