【问题标题】:.sort() not working on array ( javascript).sort() 不适用于数组(javascript)
【发布时间】:2020-08-31 14:28:06
【问题描述】:

我正在尝试通过首先创建对象来将“新货”数组与当前库存数组合并,以使数据更易于管理。因此,任何相同的项目都会添加到库存中的任何现有项目中。

.sort 运行但 flat 似乎没有做任何事情。我怀疑存在一些与我如何制作数组和弄乱索引有关的问题?

function updateInventory(arr1, arr2) {
    let invObj = {}
    let updateObj = {}
    let result = []

    arr1.forEach( x => invObj[x[1]] = x[0])
    arr2.forEach( x => updateObj[x[1]] = x[0])

    for(let key in updateObj) {
        if (invObj[key]) {
            invObj[key] += updateObj[key]
        } else {
            invObj[key] = updateObj[key]
        }
    }

    result =  Object.keys(invObj).map(key=>[invObj[key],key])
    .sort((a,b)=>{
    // attempting to sort inventory alphabetically here as required by my course's test
        return a[1] - b[1]
    })

    return result
}
var curInv = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [1, "Hair Pin"],
    [5, "Microphone"]
];

var newInv = [
    [2, "Hair Pin"],
    [3, "Half-Eaten Apple"],
    [67, "Bowling Ball"],
    [7, "Toothpaste"]
];

console.log(updateInventory(curInv, newInv));

【问题讨论】:

  • 如果您尝试对字符串进行排序,使用减法是不合适的。您应该使用字符串中的localeCompare 方法。
  • 另外,我是否建议您在构建最终结果之前对键进行排序。可以让你的代码更简洁
  • 正如其他人所写,使用localCompare 来比较字符串。你的排序测试应该是return a[1].localeCompare(b[1]);

标签: javascript sorting merge


【解决方案1】:

我会创建一个查找对象并保留对数组项的引用。在我遍历当前项目之后,我将遍历新项目。检查它是否存在并更新计数。如果它不存在,则将该项目添加到库存中。

var curInv = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [1, "Hair Pin"],
    [5, "Microphone"]
];

var newInv = [
    [2, "Hair Pin"],
    [3, "Half-Eaten Apple"],
    [67, "Bowling Ball"],
    [7, "Toothpaste"]
];

// make a look up object to reference by the key
var lookup = curInv.reduce( (obj, item) => ({ ...obj, [item[1]]: item }), {})

// loop over the new inventory and add it on
newInv.forEach((item) => {
  // check to see if we have the item
  var key = item[1]
  var exisiting = lookup[key]
  // if exists add it
  if (exisiting) {
    exisiting[0] += item[0]
  } else {
    // new item
    // add to our look up table in case it repeats
    lookup[key] = item
    // add it to the inventory list
    curInv.push(item)
  }
})

console.log(curInv)

【讨论】:

    【解决方案2】:

    对字符串进行排序时会稍微复杂一些,因为您还必须考虑大小写。这是我用js制作的表格中的sn-p,希望对您有所帮助。你可以像 taplar 所说的那样使用 localecompare。

                .sort(
                    function(a,b) {
                        a = a[1];
                        b = b[1];
                        if (a < b) {
                            return -1; 
                        } else if (a > b) {
                            return 1;
                        } else {
                            return 0; // Equal
                        }
                    });
    

    【讨论】:

      【解决方案3】:

      您是否希望数组与第一个实例中的数据格式相同?

      function updateInventory(arr1, arr2) {
          let invObj = {}
          let updateObj = {}
          let result = []
      
          arr1.forEach( x => invObj[x[1]] = x[0])
          arr2.forEach( x => updateObj[x[1]] = x[0])
      
          for(let key in updateObj) {
              if (invObj[key]) {
                  invObj[key] += updateObj[key]
              } else {
                  invObj[key] = updateObj[key]
              }
          }
          
          return invObj;
      }
      var curInv = [
          [21, "Bowling Ball"],
          [2, "Dirty Sock"],
          [1, "Hair Pin"],
          [5, "Microphone"]
      ];
      
      var newInv = [
          [2, "Hair Pin"],
          [3, "Half-Eaten Apple"],
          [67, "Bowling Ball"],
          [7, "Toothpaste"]
      ];
      
      console.log(updateInventory(curInv, newInv));

      【讨论】:

        【解决方案4】:

        在对字符串值进行排序时,您应该使用localeCompare 方法。

        function updateInventory (arr1, arr2) {
          let invObj = {};
          let updateObj = {};
          let result = [];
        
          arr1.forEach(x => invObj[x[1]] = x[0]);
          arr2.forEach(x => updateObj[x[1]] = x[0]);
        
          for (let key in updateObj) {
            if (invObj[key]) {
              invObj[key] += updateObj[key];
            } else {
              invObj[key] = updateObj[key];
            }
          }
        
          result = Object.keys(invObj)
            .sort((a, b) => a.localeCompare(b))
            .map(key => [invObj[key], key]);
        
          return result;
        }
        
        var curInv = [
          [21, 'Bowling Ball'],
          [2, 'Dirty Sock'],
          [1, 'Hair Pin'],
          [5, 'Microphone']
        ];
        
        var newInv = [
          [2, 'Hair Pin'],
          [3, 'Half-Eaten Apple'],
          [67, 'Bowling Ball'],
          [7, 'Toothpaste']
        ];
        
        console.log(
          updateInventory(curInv, newInv)
        );

        【讨论】:

          猜你喜欢
          • 2021-04-16
          • 2014-04-21
          • 1970-01-01
          • 1970-01-01
          • 2011-06-05
          • 1970-01-01
          • 1970-01-01
          • 2015-09-11
          • 2021-10-18
          相关资源
          最近更新 更多