合并排序,正确排序日期,但不排序整数值



我正在做一个编码挑战,试图学习合并排序,我已经得到我的合并排序处理日期正确,但不是一个整数值。目前它似乎是随机输出数据。

编辑:有十几个不同的帖子,比如列出的样本数据。我无法分类的对象根据他们的票数从高到低

My Merge Sort Function:

function sortBy(array, key, descending = false) {
const length = array.length;
if (length === 1) {
return array;
} else if (length === 2) {
const aValue = array[0][key];
const bValue = array[1][key];
if (bValue > aValue) {
return array;
}
return [
array[0],
array[1],
];
}
const mid = Math.floor(length / 2);
const firstHalf = array.slice(0, mid);
const secondHalf = array.slice(mid, length);
const arrayOne = sortBy(firstHalf, key);
const arrayTwo = sortBy(secondHalf, key);
const merged = [];
while (arrayOne.length || arrayTwo.length) {
if (!arrayOne.length) {
merged.push(arrayTwo.shift());
continue;
}
if (!arrayTwo.length) {
merged.push(arrayOne.shift());
continue;
}
const valueOne = arrayOne[0][key];
const valueTwo = arrayTwo[0][key];
if (valueOne <= valueTwo) {
merged.push(arrayOne.shift());
} else if (valueTwo < valueOne) {
merged.push(arrayTwo.shift());
}
}
return descending ? merged.reverse() : merged;
}

示例数据

[{
created: '2016-03-07T05:24:40.340Z',
details: 'Right now we only support single backticks. Would be nice to do triple as well... Consider supporting more or all of markdown but I'm not sure that's the right direction.',
title: 'Support triple backtick codeblocks',
votes: 17,
},]

我在阅读代码时看到的两点:

  1. 需要在最后一个返回语句
  2. 中访问数组的不同元素
const length = array.length;
if (length === 1) {
return array;
} else if (length === 2) {
const aValue = array[0][key];
const bValue = array[1][key];
if (bValue > aValue) {
return array;
}
return [
array[0], // needs to be array[1]
array[1], // needs to be array[0]
];
}
  1. 你需要在每次递归函数时传递第三个参数

    const arrayOne = sortBy(firstHalf, key, descending);

    const arrayTwo = sortBy(secondHalf, key, descending);

相关内容

  • 没有找到相关文章

最新更新