二维数组,过滤并返回带有索引而不是值的新数组

问题描述 投票:0回答:2

我有一个二维数组,它又包含一个带有附加数组的对象。

我想过滤数组并返回一个新数组,其索引与对象的条件匹配。

例如:

一个数组:gp[0][0].pts = [10,5,40,30,95,5,11,85]; 我想搜索数组并返回大于或等于 20 的值。这将是 [40, 30, 95, 85];

我希望新数组返回这些索引,因此在本例中它将是 [2,3,4,7]

下面的代码返回正确的数字,但我想要索引。

提前致谢。

const gp = [
  [{
    "pts": [10, 5, 40, 30, 95, 5, 11, 85]
  }, {
    "pts": [2, 1, 4]
  }, {
    "pts": [14, 22, 41, 23]
  }]
];


for (let n = 0; n <= 2; n++) {
  const race = gp[0][n].pts.filter(v => +v >= 20).map(Number);
  if (race.length) {
    console.log(`race at n=${n}: ${race}`);
  };
};

javascript arrays object filter
2个回答
0
投票

您可以通过以下方式实现这一目标

1-
将每个值映射到包含值和索引的对象

2-
过滤值 >= 20 的对象

3-
映射回索引

let gp = [];
gp[0] = [];
gp[0][0] = {};
gp[0][0].pts = [10, 5, 40, 30, 95, 5, 11, 85];

gp[0][1] = {};
gp[0][1].pts = [2, 1, 4];

gp[0][2] = {};
gp[0][2].pts = [14, 22, 41, 23];



const filteredIndicesPerRace = {};

gp[0].forEach((race, raceIndex) => {
  filteredIndicesPerRace[raceIndex] = race.pts
    .map((value, index) => ({
      value,
      index
    })) 
    .filter(obj => obj.value >= 20) 
    .map(obj => obj.index); 
});

console.log(filteredIndicesPerRace);


0
投票

首先,将数组映射到[元素,索引]对。然后过滤,然后仅提取索引。

const gp = [
  [{
    "pts": [10, 5, 40, 30, 95, 5, 11, 85]
  }, {
    "pts": [2, 1, 4]
  }, {
    "pts": [14, 22, 41, 23]
  }]
]

gp[0].forEach(({pts}, n) => {
  let race = pts.map((e,i) => [e,i]).filter(([e]) => +e >= 20).map(([e,i]) => i)
  if(race.length) console.log(`race at n=${n}: ${race}`)
})

© www.soinside.com 2019 - 2024. All rights reserved.