简体   繁体   English

JavaScript - 从二维数组中过滤数组

[英]JavaScript - Filtering an array from 2D array

I'm attempting to add a condition to my 2D array that I am getting back from an API call.我正在尝试向我从 API 调用返回的二维数组添加一个条件。 The data being returned is a top 3 rankings for state.返回的数据是 state 的前 3 名。 So for example, there are 3 values that read "California" with the second index being the rank.例如,有 3 个值读取“加利福尼亚”,第二个索引是排名。 I am attempting to apply a condition to filter out any state that does not return appear 3 times, for example: If (state name) does not have 1, 2, 3 dont return.我正在尝试应用一个条件来过滤掉任何不返回的 state 出现 3 次,例如:如果(状态名称)没有 1、2、3 则不返回。 My issue is that I do not know how to apply this logic successfully.我的问题是我不知道如何成功应用这个逻辑。

I've attempted looping through an array and putting a condition if the state name does not happen 3 times, remove from the array.如果 state 名称没有出现 3 次,我尝试循环遍历数组并设置条件,从数组中删除。

My expected result would be this:我的预期结果是:

const data = [ [ "California", 1 , 23432], ["Califonria", 2, 22132], ["California", 3, 49343], ["New York", 1, 3231], ["New York", 2 , 3023], ["New York", 3, 2932]

here is a snippet that i've tried:这是我尝试过的一个片段:

 const data = [ [ "California", 1, 23432], ["Califonria", 2, 22132], ["California", 3, 49343], ["New York", 1, 3231], ["New York", 2, 3023], ["New York", 3, 2932], ["Georgia", 1, 3423]] for (let i = 0; data.length > i; i++) { if (data[0].length < 3) { data.splice(i,1) } } console.log(data)

You can build a count of how many times each state name occurs in your original array and then filter the array based on the count being 3 for that state name:您可以计算每个 state 名称在原始数组中出现的次数,然后根据该 state 名称的计数为 3 过滤数组:

 const data = [ ["California", 1, 23432], ["California", 2, 22132], ["California", 3, 49343], ["New York", 1, 3231], ["New York", 2, 3023], ["New York", 3, 2932], ["Georgia", 1, 3423] ]; const counts = data.reduce((c, v) => { c[v[0]] = (c[v[0]] || 0) + 1; return c; }, {}); const result = data.filter(v => counts[v[0]] == 3); console.log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM