在数组中查找元素的最佳方法是什么?

时间:2020-03-16 10:28:28

标签: javascript arrays reactjs

我有一个包含患者列表的数组,他们都有唯一的ID。

 this.state = { 
  patients = [
        {id: "1", name: "Joe", age: 6, location: ''},
        {id: "12", name: "Her", age: 2, location: ''},
        {id: "1123", name: "Jin", age: 10, location: ''},
        {id: "11234", name: "Nick", age: 23, location: ''},
        {id: "12345", name: "Fil", age: 50, location: ''},
    ];

当用户单击按钮时,它将发送唯一的唯一ID和回调中的位置。然后,我使用唯一的ID在患者数组中查找患者并更新该患者的位置。我在阵列中找到患者的方式是使用map遍历患者阵列,检查是否 patientId与数组中的id相匹配,并添加该患者的位置。但是,地图将永远遍历每一个 patients array中的“病人”,因此不必要的循环也很麻烦,而且如果数组变大,代价会很高。我知道还有其他方法可以在 数组,即findIndex() method,但它比地图好吗?此用例的最佳方法是什么?

 <Button 
    id={location} 
    onClick={() => addPatientLocation(patientId, location}
 > 
    {location}
</Button>

检查患者ID是否匹配并更新患者详细信息的功能

  addPatientLocation(patientId, location) {
        this.setState(prevState => ({

            patients: prevState.patients.map(p => {
                if (p.id === patientId) {
                    return { ...p, location: location };
                }
                return p;
            }),
        }));
    }

3 个答案:

答案 0 :(得分:2)

我的示例使用了findIndex。我对findIndex和map函数进行了基准测试,请参见下面的结果。基准测试显示findIndex更快。

var t1 = performance.now();
const patients = [
        {id: "1", name: "Joe", age: 6, locaiton: ''},
        {id: "12", name: "Her", age: 2, locaiton: ''},
        {id: "1123", name: "Jin", age: 10, locaiton: ''},
        {id: "11234", name: "Nick", age: 23, locaiton: ''},
        {id: "12345", name: "Fil", age: 50, locaiton: ''},
    ];
 
const index = patients.findIndex((elem) => elem.id =="11234");
patients[index].location="Location";
console.log(patients[index]);
var t2 = performance.now();   
console.log("time consumption", (t2 - t1));

var t1 = performance.now();
const patients = [
        {id: "1", name: "Joe", age: 6, locaiton: ''},
        {id: "12", name: "Her", age: 2, locaiton: ''},
        {id: "1123", name: "Jin", age: 10, locaiton: ''},
        {id: "11234", name: "Nick", age: 23, locaiton: ''},
        {id: "12345", name: "Fil", age: 50, locaiton: ''},
    ];
 
const obj = patients.map((elem, index) => {
  if (elem.id =="11234") {
    return { ...elem, locaiton: "Location" };
  }
  return elem;
});
console.log(obj[3]);
var t2 = performance.now();   
console.log("time consumption", (t2 - t1));

答案 1 :(得分:1)

您可以使用findIndex

let patients = [...this.state.patients]
let index = patients.findIndex(t=>t.id == patientId)
patients[index] = { ...patients[index], location: value }
this.setState({patients})

答案 2 :(得分:0)

可以使用Map代替Array吗?它将使患者更快地获得id。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map