简体   繁体   English

根据对象数组中的值对 DOM 元素进行排序的最有效方法是什么?

[英]What is the most efficient way to sort DOM elements based on values in an array of objects?

I have a series of divs that display data on different people.我有一系列 div 显示不同人的数据。 The data for each person is stored in an array of objects, and there are a lot of values for each person.每个人的数据存储在一个对象数组中,每个人都有很多值。 There is a button for each property, and I would like to be able to sort the divs in ascending or descending order of a property by clicking on a button.每个属性都有一个按钮,我希望能够通过单击按钮按属性的升序或降序对 div 进行排序。 Each div is given an id, that corresponds to an id of the associated person in the array.每个 div 都有一个 id,它对应于数组中相关人员的 id。

The data looks like (but it is much larger than this):数据看起来像(但比这大得多):

people = [
   {
     id: 'xde234',
     height: '196',
     weight: '100',
     age: '34'
  },
  {
     id: 'sbd451',
     height: '176',
     weight: '140',
     age: '26'
  },
  {
     id: 'loe489',
     height: '156',
     weight: 'NA',
     age: '54'
  }]

The data for each person is displayed by looping through the data, creating a div for each person, assigning their id as the id of the div, and defining the inner html of a span with each property value.每个人的数据通过循环数据显示,为每个人创建一个 div,将他们的 id 分配为 div 的 id,并使用每个属性值定义一个 span 的内部 html。 The class name of the span is the same as the property.跨度的类名与属性相同。 So the HTML looks likes:所以 HTML 看起来像:

<div id="peopleContainer">
  <div id='xde234'>
     <span class="height">196</span>
     <span class="weight">100</span>
     <span class="age">34</span>
  </div>
  <div id='sbd451'>
     <span class="height">176</span>
     <span class="weight">140</span>
     <span class="age">26</span>
  </div>
  <div id='loe489'>
     <span class="height">156</span>
     <span class="weight">NA</span>
     <span class="age">54</span>
  </div>
</div>

Each button is created with an eventlistener eg:每个按钮都是用一个事件监听器创建的,例如:

heightButton = document.getElementById('heightButton')
heightButton.addEventListener('click', function(){
   // sortingFunction
}

I have been retrieving the divs and writing a sorting function using :我一直在检索 div 并使用以下方法编写排序函数:

function sortingFunction(property){

   peopleContainer = document.getElementById('peopleContainer')
   allPeople =  peopleContainer.children
}

I have 3 questions really, the main one being the first:我真的有3个问题,主要是第一个:

  1. What is the most efficient way to sort and display this data in javascript for any property in the data, considering there will be many people and a large number of properties考虑到会有很多人和大量属性,在javascript中为数据中的任何属性排序和显示此数据的最有效方法是什么?

  2. How do I implement ascending and descending sort into one button, so it alternates between the two.如何在一个按钮中实现升序和降序排序,以便在两者之间交替。

  3. When a button is clicked, regardless of if it is ascending or descending, I would like all the NA values to be at the bottom, ie they are ignored in the sort but appended to the end.当一个按钮被点击时,无论它是升序还是降序,我都希望所有的 NA 值都在底部,即它们在排序中被忽略但附加到末尾。

Any help is greatly appreciated.任何帮助是极大的赞赏。

It may help to create a new data structure holding references to the DOM elements.创建一个新的数据结构来保存对 DOM 元素的引用可能会有所帮助。

const peopleElements = {}
[...allPeople].forEach(node=>{
  peopleElements[node.id] = node;
});

Next you can sort your people array however you like.接下来,您可以根据自己的喜好对people数组进行排序。 Once that's done, you can refresh the container:完成后,您可以刷新容器:

people.forEach(person=>{
  const node = peopleElements[person.id];
  peopleContainer.append(node);
});

Note that appending an element that's already on the page will simply move it to the end.请注意,附加一个已经在页面上的元素只会将其移动到末尾。 Moving each person to the end in turn will result in the elements appearing in sorted order.依次将每个人移动到最后将导致元素按排序顺序出现。

thanks to @NiettheDarkAbsol his answer combined with the following sort functions has led me to a working answer.感谢@NiettheDarkAbsol,他的回答结合以下排序功能使我得到了一个有效的答案。 I use the data attribute to store the last type of sort (asc or desc).我使用 data 属性来存储最后一种排序类型(asc 或 desc)。 I use @NiettheDarkAbsol suggestion to append nodes, but do it twice, the second time with a condition to check for NAs, then move them to the bottom which works as desired.我使用@NiettheDarkAbsol 建议来附加节点,但做两次,第二次有条件检查 NA,然后将它们移动到底部,按需要工作。 The sorting function now is :现在的排序功能是:

function sortingFunction(e, property){

    peopleContainer = document.getElementById('peopleContainer');
    allPeople =  peopleContainer.children;

    const peopleElements = {};

    [...allPeople].forEach(node=>{
    peopleElements[node.id] = node;
    });
  
    if(e.target.getAttribute('data-lastSort') === 'desc'){
        e.target.setAttribute('data-lastSort','asc')
        people.sort(function(a,b){
            return a[property] - b[property]
        });
    }else{
        e.target.setAttribute('data-lastSort','desc')
        people.sort(function(a,b){
            return a[property] + b[property]
        });
    };
   
    people.forEach(person=>{
    const node = peopleElements[person.id];
    peopleContainer.append(node);
    };

    people.forEach(person=>{
       if(person[property] === 'NA'){
       const node = peopleElements[person.id];
       peopleContainer.append(node);
       };
    });

};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Js:将对象数组排序为部分的最有效方法是什么? - Js: What is the most efficient way to sort an array of objects into sections? 根据另一个元素的状态切换DOM元素值的最有效方法是什么? - What is the most efficient way of toggling a DOM elements value based on the state of another element? 在不重新渲染RactiveJS中的整个DOM的情况下,用对象更新数组的最有效方法是什么? - What is the most efficient way to update an array with objects without re-rendering the entire DOM in RactiveJS? 在jQuery中访问DOM元素的最有效方法是什么? - What is the most efficient way to access DOM elements in jQuery? 修改DOM元素和限制重排的最有效方法是什么? - What is the most efficient way to modify DOM elements and limit reflow? 比较两个对象的值的最有效方法是什么? - What's the most efficient way to compare values of two objects? 使用值数组选择所有元素的最有效方法 - Most efficient way to select all elements with an array of values 在对象数组中循环属性的最有效方法是什么? - What is the most efficient way to loop on properties in array of objects? 将对象数组转换为对象的最有效方法是什么 - What is the most efficient way to convert an array of objects to an object 在DOM中更新图像的最有效方法是什么? - What is the most efficient way to update images in the DOM?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM