简体   繁体   中英

Sort, search in object javasript

I would like to be able to search, filter and sort in an object. Below is the code of the object. I have an input field where I can search in the object. It is also the intention that I can indicate what I want to search + ascending or descending.

在此处输入图片说明

In the picture you can see what the html looks like.

This is the code to search and sort

 const users = [{ id: 1, name: "Jan", age: 17, city: "Dublin", }, { id: 2, name: "Bob", age: 17, city: "London", } ]
 <form action="#" method="post" id="filters"> <label for="search">Search</label><input type="search" name="search" id="search" /> <label>Sort items by <select id="sortby" name="sortby"> </select> </label> <select id="direction" name="direction"> <option value="asc">ascending</option> <option value="desc">descending</option> </select> </form>

function assending(a, b){
    var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase()
    if (nameA < nameB) 
        return -1 
    if (nameA > nameB)
        return 1
    return 0 
}

function desending(a, b){
    var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase()
    if (nameA > nameB) 
        return -1 
    if (nameA < nameB)
        return 1
    return 0 
}

//filter Data
var filterData = users.filter(x=>x.name.indexOf(searchText) > -1);

var result = [];
//Sort Data
if(accending){
   result =  filterData.sort(assending)
}else{
   result =  filterData.sort(desending)
}

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