如果为其中一个重复项设置了值,则如何从数组中删除重复项,否则为空(javascript/typescript)

yqkkidmi  于 2023-01-03  发布在  TypeScript
关注(0)|答案(2)|浏览(95)

我需要从javascript(typescript)的数组中删除重复的或空的值(集合),如果在同一天有非空值的数据,如果所有的值(集合)在那天都是空的,我们应该保留一个值。

示例:

0: (2) ['2022-12-05', null]   ---> Remove due to "Reason 1"
1: (2) ['2022-12-05', 2695.923015841]   ---> Remain because it has a y value (on 5 Dec)
2: (2) ['2022-12-05', null]   ---> Remove due to "Reason 1"
3: (2) ['2022-12-05', null]   ---> Remove due to "Reason 1"

4: (2) ['2022-12-12', null]   ---> Remove due to "Reason 1"
5: (2) ['2022-12-12', 3984.864626441]   ---> Remain because it has a y value (on 12 Dec)
6: (2) ['2022-12-12', null]   ---> Remove due to "Reason 1"
7: (2) ['2022-12-12', null]   ---> Remove due to "Reason 1"

8: (2) ['2022-12-19', null]   ---> Remove due to "Reason 2"
9: (2) ['2022-12-19', null]   ---> Remove due to "Reason 2"
10: (2) ['2022-12-19', null]   ---> Remove due to "Reason 2"
11: (2) ['2022-12-19', null]   ---> Remain because no y value on this date
    • 原因1**:数组的这个成员应该被删除,因为在同一个日期有一个空值(在x中指定)。
0: (2) [x: Date, y: value]
    • 原因2**:这个成员应该被删除,因为我们有4个相同值的重复对象,我们只需要其中的一个。

预期结果:

它将是一个具有3个值(集)的数组。

0: (2) ['2022-12-05', 2695.923015841]   ---> Remain because it has a y value 
1: (2) ['2022-12-12', 3984.864626441]   ---> Remain because it has a y value 
2: (2) ['2022-12-19', null]   ---> Remain because no y value on this date
gcxthw6b

gcxthw6b1#

您可以使用单个循环来缩减数组,并检查date

const
    data = [['2022-12-05', null], ['2022-12-05', 2695.923015841], ['2022-12-05', null], ['2022-12-05', null], ['2022-12-12', null], ['2022-12-12', 3984.864626441], ['2022-12-12', null], ['2022-12-12', null], ['2022-12-19', null], ['2022-12-19', null], ['2022-12-19', null], ['2022-12-19', null]],
    result = data.reduce((r, [date, value], i, a) => {
        if (i && a[i - 1][0] === date) r.at(-1)[1] ||= value;
        else r.push([date, value]);
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
t1rydlwq

t1rydlwq2#

const arr = [
  ['2022-12-05', null],
  ['2022-12-05', 2695.923015841],
  ['2022-12-05', null],
  ['2022-12-05', null],
  ['2022-12-12', null],
  ['2022-12-12', 3984.864626441],
  ['2022-12-12', null],
  ['2022-12-12', null],
  ['2022-12-19', null],
  ['2022-12-19', null],
  ['2022-12-19', null],
  ['2022-12-19', null],
];

const newArr = [...new Set(arr.map(item => item[0]))].map(item => {
  const findVal = arr.find(_item => _item[0] === item && _item[1]);
  if (findVal) return findVal;
  return [item, null];
});

console.log(newArr);

相关问题