-2

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.

enter image description here

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
TJE
  • 33
  • 2
  • 1
    Somebody has had done it already. https://stackoverflow.com/questions/1069666/sorting-object-property-by-values – Lhew Dec 07 '19 at 15:24
  • I made you a snippet and quoted your values – mplungjan Dec 07 '19 at 15:28
  • 2
    Does this answer your question? [Sorting object property by values](https://stackoverflow.com/questions/1069666/sorting-object-property-by-values) – henriquehbr Dec 07 '19 at 15:35

1 Answers1

0
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)
}