quick Sortfunction Array by specific value

百般思念 提交于 2020-06-29 06:41:30

问题


Full Code at https://codepen.io/CodeLegend27/pen/ExPZRxa

did read similary articles but didnt managed to solve it

so my array looks like this:

I have this loop

for (let i = 0; i < ultraarr.length; i++) {
  ultraarr.sort();
  $(".row").append(ultraarr[i].display())
}

this calls the function display which is a class function and it basically inserts the data into html. What i want it to DO:

i want it ordered according to the dates ascending. did research the a-b stuff but cant see the solution for me

CLASS FUNCTION for your INFO:

 display() {
    let content =
      `
      <div class="col-sm-12 col-md-6 col-lg-3">
      <div class="card">
      <img class="card-img-top d-sm-none d-md-block" src="img/${this.img}" alt="${this.name}">
      <div class="card-body">
        <h5 class="card-title">${this.name}</h5>
        <p class="card-text">City: ${this.city} Zip-Code ${this.zip}
        <br>
        <label> Event Infos </label>
        <ul>
        <li>${this.edate}</li>
        <li>${this.etime}</li>
        <li>${this.eprice}</li>
        <li>${this.eweb}</li>
        </ul>
        <p>Created: ${this.dates.toLocaleString('de-AT')}
        </p>
            </div></div>
    </div>
      ` ;
    return content;
  }

btw before the dates are passed to the class constructor they created like this: new Date(2011, 1, 1, 3, 25), and when i console log for example typeof(newClassItem.dates) it says object and not number or string so i dont really know how to do it - i thought maybe with .valueOf?


回答1:


When you are saving the dates, save them using toJSON methond on the Date Object. Pass the sort function to the array sort function.

var array = [
  {'name':'test1','date':'2020-06-19T14:21:31.633Z'},
  {'name':'test2','date':'2020-07-30T12:22:53.113Z'},
]

function sortDate(rec1,rec2){
  return new Date(rec1.date) < new Date(rec2.date) ? -1 : 1
}

array.sort(sortDate)

console.log(array)

This is will sort the array in ascending order. If you want to sort it in descending order, either change the comparison sign to '>' or swap -1 and 1.

If the array internal is storing date field as dates data type, you can do the following

function sortDate(rec1,rec2){
  return rec1.date < rec2.date ? -1 : 1
}

ultraarr.sort(sortDate)


来源:https://stackoverflow.com/questions/62472047/quick-sortfunction-array-by-specific-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!