Reputation: 11
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:
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
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
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