Kaizrr
Kaizrr

Reputation: 11

Check if 2 input match an array element in a 2D array

Basically, I have a very big 2D array that contains thousands of array represent data of zip code and city in a form like this ['14167', 'Berlin'].
What I need to do is checking the input of zip code and city from a form to see if it match the data from the array and:

  1. If the city cannot be found in the array, then show an error alert.
  2. If the city is found but the zip code does not match, show a window that said "did you mean this?" and insert the right zip code in the form automatically.
  3. If the city and zip code match, show a window that says it matches, and then the form should be reset.

What i have written so far:

function zipCheck(arr,k){
    var check=[];
    for (var i = 0; i < arr.length; i++) {
        var index = arr[i].indexOf(k);
        if (index > -1) {
            var val = index - 1;
            check.push(arr[i][val]);
            return check;
        }
    }
}

What I tried to do here is that I tried to use indexOf to check the position of the city input and use that position to push the matching zip codes to a different array. Then I will try to check the zip code input value to see if it match any element of the pushed array. The problem with my code is that I can only push the first zip code value to the check array while there might still be zip codes that match that city. Example: ['14131','Berlin'],['14163','Berlin'],['14165','Berlin'].

Can someone help me fix my code or is there a more efficient way to do this? Thanks in advance

Upvotes: 1

Views: 217

Answers (2)

a.mola
a.mola

Reputation: 4011

You need to pass both the city and zipcode to the function

Filtering through the 2D array to check for all items with a city, then map out the zipcodes.

First, I check if the check variable has any elements in it which mean there are cities, then i check if the passed zip code exists. If it doesn't it offers the first element in our check variable. Else it alerts match

function zipCheck(arr, city, zip) {
  const check = arr.filter(item => item[1] == city).map(item => item[0]);
  
  if (!check.length) console.log(`City ${city} does not exist`);
  else if (check.findIndex(item => item == zip) > -1) console.log(`Couldn't find zipcode ${zip} did you mean ${check[0]}`)
  else console.log(`Matched ${city}, ${zip}`);
}

const data = [['14131','Berlin'],['14163','Berlin'],['14165','Berlin']];

zipCheck(data, 'Berlin');
zipCheck(data, 'Home');

Upvotes: 0

Barmar
Barmar

Reputation: 781096

You can use filter() to find all the elements for the city. Then use some() to test if any of them have the entered zip code.

function zipCheck(arr, city, zip) {
  let items = arr.filter(el => el[1] == city);
  if (!items) {
    alert(`City ${city} not found`);
  } else if (!items.some(el => el[0] == zip)) {
    alert(`Zip ${zip} is not found for ${city}`);
  }
}

Upvotes: 1

Related Questions