0

I'm attempting to add a condition to my 2D array that I am getting back from an API call. The data being returned is a top 3 rankings for state. So for example, there are 3 values that read "California" with the second index being the rank. 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. 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.

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)

2
  • Your question is a bit confusing, what are you trying to do? Filter all sub arrays that their length is less than 3? Then you code seems to work, Can you provide an example of an good input you want to keep and a bad input you want to filter out? Commented Jul 31, 2020 at 23:32
  • 1
    sorry, i'll try and be a bit more clear. I'm attempting to remove any state such as in this example "Georgia" that does not have a value of 2 and 3. The index of 1 in these arrays would be there rank. So I'm attempting to display a top 3 values for each state, so for the ones that do not have 3 values i'd like to have them filtered from the array. Hope that clarifies. Commented Jul 31, 2020 at 23:34

1 Answer 1

3

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:

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.