为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

繁花如伊 2023-06-29 15:38:56
我正在尝试使用 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']);});}有人对我如何解决这个问题有任何建议吗?非常感谢!
查看完整描述

2 回答

?
慕后森

TA贡献1802条经验 获得超5个赞

您的问题不在于“排序”,而是您覆盖了 SortElements 对象中的键


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

如果下一个商品具有相同的价格,那么您将使用新的 {element, index} 覆盖 SortElements[that Price];


我不想插入到一个对象中..插入到一个数组中


function myFunction() {

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

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

  var parent = y[0];

  var SortElements = [];

  items.forEach(function(item, indx){

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

    SortElements.push({'element': item, 'price':itemValue, 'index': indx});

  });

  function compareNumeric(a, b) {

    numA = a.price;

    numB = b.price;


    if (numA < numB) return 1;

    if (numA > numB) return -1;

    return 0;

  }

  SortElements.sort(compareNumeric);

  SortElements.forEach(function(item){

    parent.insertAdjacentElement('beforeend', item.element);

  });

}


查看完整回答
反对 回复 2023-06-29
?
尚方宝剑之说

TA贡献1788条经验 获得超4个赞

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



查看完整回答
反对 回复 2023-06-29
  • 2 回答
  • 0 关注
  • 99 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信