猿问

在JS中按价格对项目数组进行排序忽略具有相同价格的元素

我正在尝试使用 Javascript 订购产品列表,并且该脚本运行良好,但如果两种产品具有相同的价格,则脚本只会忽略其中一个。


function myFunction() {var items = document.querySelectorAll('.vc_visible-item');

var y = document.getElementsByClassName('vc_pageable-slide-wrapper');

var parent = y[0];

var SortElements = new Object();

items.forEach(function(item, indx){

  var itemValue = parseFloat(item.querySelector('.price-product').textContent.replace('€', '').replace(/\s+/g, ''));

  SortElements[itemValue] = {'element': item, 'index': indx} ;

});

var keys = Object.keys(SortElements);

function compareNumeric(a, b) {

  a = parseInt(a);

  b = parseInt(b);


  if (a <= b) return 1;

  if (a >= b) return -1;

 

}

keys.sort(compareNumeric);

keys.map(function(key, indx){

  parent.insertAdjacentElement('beforeend', SortElements[key]['element']);

});

}

有人对我如何解决这个问题有任何建议吗?非常感谢!


繁花如伊
浏览 145回答 2
2回答

慕后森

您的问题不在于“排序”,而是您覆盖了 SortElements 对象中的键SortElements[itemValue] = {'element': item, 'index': indx}如果下一个商品具有相同的价格,那么您将使用新的 {element, index} 覆盖 SortElements[that Price];我不想插入到一个对象中..插入到一个数组中function myFunction() {&nbsp; var items = document.querySelectorAll('.vc_visible-item');&nbsp; var y = document.getElementsByClassName('vc_pageable-slide-wrapper');&nbsp; var parent = y[0];&nbsp; var SortElements = [];&nbsp; items.forEach(function(item, indx){&nbsp; &nbsp; var itemValue = parseFloat(item.querySelector('.price-product').textContent.replace('€', '').replace(/\s+/g, ''));&nbsp; &nbsp; SortElements.push({'element': item, 'price':itemValue, 'index': indx});&nbsp; });&nbsp; function compareNumeric(a, b) {&nbsp; &nbsp; numA = a.price;&nbsp; &nbsp; numB = b.price;&nbsp; &nbsp; if (numA < numB) return 1;&nbsp; &nbsp; if (numA > numB) return -1;&nbsp; &nbsp; return 0;&nbsp; }&nbsp; SortElements.sort(compareNumeric);&nbsp; SortElements.forEach(function(item){&nbsp; &nbsp; parent.insertAdjacentElement('beforeend', item.element);&nbsp; });}

尚方宝剑之说

在循环中,您使用项目的值作为每个属性的名称在对象items.forEach中创建成员。SortElements如果循环发现具有该名称的成员已存在,它将用遇到的新值替换该属性的当前值。您可以在该行周围放置一个条件来检查该属性是否存在。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答