在JavaScript

时间:2018-01-16 17:15:06

标签: javascript sorting reduce

我正在尝试在reduce内进行排序,我认为我的一切都是正确的,但我的结果仍未按要求排序。

以下是我的代码段:

var studentInfo = [
{
    studentId: 1,
    addresses: [
        {street: '123 Main St'},
    ]
},
{
    studentId: 2,
    addresses: [
        {street: '456 Front St'}
    ]
},
{
    studentId: 3,
    addresses: [
        {street: '100 MLK St'}
    ]
}
];

function appendAddress(studentId, newAddress) {
  return studentInfo.reduce(function (info, student) {
    if (student.studentId === studentId) {
        student = {
            studentId: student.studentId,
            addresses: student.addresses.concat(newAddress).sort(function (address1, address2) {
                return address2.street - address1.stree;
            })
        };
    }
    info.push(student);

    return info;
}, []);
}

var newAddress = {
street: '166 Devil St'
}

console.log('Result: ' + JSON.stringify(appendAddress(2, newAddress)));

我的结果为

Result: [{"studentId":1,"addresses":[{"street":"123 Main St"}]},{"studentId":2,"addresses":[{"street":"456 Front St"},{"street":"166 Devil St"}]},{"studentId":3,"addresses":[{"street":"100 MLK St"}]}]

而不是

Result: [{"studentId":1,"addresses":[{"street":"123 Main St"}]},{"studentId":2,"addresses":[{"street":"166 Devil St"},{"street":"456 Front St"}]},{"studentId":3,"addresses":[{"street":"100 MLK St"}]}]

我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

关于排序问题,如果这是你想知道的主要问题,你确实有一个错字作为上面提到的评论,而且,对非数字字符串执行减法不会让你走得太远。我在上面的解决方案中使用了.localeCompare

如果您想在追加时复制对象,那仍然可以更简单地完成,但我不知道这是否是您真正想要的。

var studentInfo = [
  {studentId: 1,addresses: [{street: '123 Main St'}]},
  {studentId: 2,addresses: [{street: '456 Front St'}]},
  {studentId: 3,addresses: [{street: '100 MLK St'}]}
];

console.log(addAddress(2, {street: "1234 56th Ave"}));

function addAddress(studentId, address) {
  const idx = studentInfo.findIndex(o => o.studentId === studentId);
  if (idx !== -1) {
    return [...studentInfo.slice(0, idx), {
      studentId,
      addresses: [...studentInfo[idx].addresses, address].sort((a,b) => a.street.localeCompare(b.street))
    }, ...studentInfo.slice(idx+1)];
  } else {
    return [...studentInfo, {studentId, addresses:[address]}];
  }
}

但是现在你有两个不同的数据副本和一些共享对象。