简体   繁体   中英

Check to see if an array element already exists

I have implemented function to add a name to an array which then will be displayed into a table on a page.

The next question I have is, how do I check whether a first and last name already exist in the array. My function is below, once I know how to handle the check I will add it to the function.

function addNewGuest(event) {
    event.preventDefault()
    let f = document.querySelector("#first_name").value
    let l = document.querySelector("#last_name").value
    let names = getGuestList()

    if (f || l) {
        alert("First and Last name required.")
    }
    
    if (f && l) {
        let name = { fName: f, lName: l }
        names.push(name)
        localStorage.setItem('names', JSON.stringify(names))
    }
    displayGuestList()
    document.querySelector("#first_name").value = ''
    document.querySelector("#last_name").value = ''
}

使用Array.prototype.find搜索一个人,如果find方法返回undefined ,则该人不存在,所以我们翻转为布尔值。

const alreadyExists = names.find(({fName, lName}) => fName === f && lName === l) !== undefined;

You would have to loop over the array and check each element to make sure it exists.

An easy way to do so would be to use the some helper function on arrays.

// check if a name with the same first and last name already exists
function nameExists(input, namesList) {
  return namesList.some(name => (input.f === name.f) && (input.l === name.l);
}

However, looping over each item is pretty inefficient for very large datasets so you may be better off looking into using data structures like a Set or even a regular object which are tailored for looking up key/value pairs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM