TypeScript数组排序与可选属性预期不同。

huangapple go评论72阅读模式
英文:

TypeScript Array Sort Not Working as Expected with Optional Property

问题

我正在尝试在TypeScript中根据可选属性ind对对象数组进行排序如果a和b都具有ind属性我希望根据ind以降序对数组进行排序否则如果a或b或两者缺少ind属性则根据createdAt属性以升序对数组进行排序

这是我的排序代码

```typescript
const sortedArray = arrayToSort.sort((a, b) => {
  if (a.ind && b.ind) {
    return b.ind - a.ind; // 根据ind以降序排序
  } else {
    return (
      new Date(a.createdAt).getTime() -
      new Date(b.createdAt).getTime()
    ); // 根据createdAt以升序排序
  }
});

然而,排序似乎并没有按预期工作,结果没有正确排序。

数组元素具有以下结构:

interface ArrayElement {
  ind?: number;
  createdAt: string;
  // 其他属性...
}
英文:

I am trying to sort an array of objects in TypeScript based on an optional property ind. If both a and b have the ind property, I want to sort the array in descending order based on ind. Otherwise, if either a or b (or both) lacks the ind property, I want to sort the array in ascending order based on the createdAt property.

Here's my sorting code:

const sortedArray = arrayToSort.sort((a, b) => {
  if (a.ind && b.ind) {
    return b.ind - a.ind; // Sort by ind in descending order
  } else {
    return (
      new Date(a.createdAt).getTime() -
      new Date(b.createdAt).getTime()
    ); // Sort by createdAt in ascending order
  }
});

However, the sorting does not seem to work as expected, and the result is not sorted correctly.

The array elements have the following structure:

interface ArrayElement {
  ind?: number;
  createdAt: string;
  // other properties...
}

答案1

得分: 0

从你的界面来看,似乎你的类型是数字,如果"ind"的值为0,它将被视为false,即使在这种情况下,条件也不会满足。

解决方法是这样检查键的可用性。

if (a.ind !== undefined && b.ind !== undefined) {
    return b.ind - a.ind;
  } else {
    // 代码的其余部分....
}

或者

if (a.hasOwnProperty('ind') && b.hasOwnProperty('ind')) {
    return b.ind - a.ind;
  } else {
    // 代码的其余部分....
}
英文:

From your interface it seems you ind type is number, if ind is 0 it will be considered as false and even if there is ind in that situation that condition wont be satisfied.

Solution is to check for key availability this way.
`

if (a.ind !== undefined && b.ind !== undefined) {
    return b.ind - a.ind;
  } else {
    rest of the code....

OR

if (a.hasOwnProperty('ind') && b.hasOwnProperty('ind')) {
    return b.ind - a.ind;
  } else {
    rest of the code...

答案2

得分: 0

如“ind”属性是可选的,TypeScript 不能保证“a.ind”和“b.ind”始终定义。

根据您当前的代码,当“a.ind”和“b.ind”都可用时,您直接减去了“ind”值。为了消除TypeScript错误,您可以检查“undefined”值。

演示示例 :

const arrayToSort = [{
  ind: 1
}, {
  ind: 5
}, {
  ind: 8
}, {
  ind: undefined
}, {
  ind: 7
}, {
  ind: 2
}]

const sortedArray = arrayToSort.sort((a, b) => {
  if (a?.ind !== undefined && b?.ind !== undefined) {
    return b.ind - a.ind;
  } else if (a?.ind !== undefined) {
    return -1; // 将 'a' 放在 'b' 之前
  } else if (b?.ind !== undefined) {
    return 1; // 将 'b' 放在 'a' 之前
  } else {
    return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
  }
});

console.log(sortedArray);

希望这能帮助您理解代码的翻译部分。

英文:

As ind property is optional, Typescript can not guarantee that a.ind and b.ind are always defined.

As per your current code, You are directly subtract the ind values when both a.ind and b.ind are available. To get rid from typescript error, You can check for undefined values.

Live Demo :

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const arrayToSort = [{
  ind: 1
}, {
  ind: 5
}, {
  ind: 8
}, {
  ind: undefined
}, {
  ind: 7
}, {
  ind: 2
}]

const sortedArray = arrayToSort.sort((a, b) =&gt; {
  if (a?.ind !== undefined &amp;&amp; b?.ind !== undefined) {
    return b.ind - a.ind;
  } else if (a?.ind !== undefined) {
    return -1; // Move &#39;a&#39; before &#39;b&#39;
  } else if (b?.ind !== undefined) {
    return 1; // Move &#39;b&#39; before &#39;a&#39;
  } else {
    return
      new Date(a.createdAt).getTime() -
      new Date(b.createdAt).getTime()
  }
});

console.log(sortedArray);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月20日 09:16:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76726095.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定