Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Checking existence of all continents in array of objects in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of objects that contains data about the continent of belonging for some people.
Our function should return true if it finds six different continents in the array of objects, false otherwise.
Example
Following is the code −
const people = [
{ firstName: 'Dinesh', lastName: 'A.', country: 'Algeria', continent: 'Africa', age: 25, language: 'JavaScript' },
{ firstName: 'Ishan', lastName: 'M.', country: 'Chile', continent: 'South America', age: 37, language: 'C' },
{ firstName: 'Rohit', lastName: 'X.', country: 'China', continent: 'Asia', age: 39, language: 'Ruby' },
{ firstName: 'Manpreet', lastName: 'P.', country: 'Andorra', continent: 'Europe', age: 55, language: 'Ruby' },
{ firstName: 'Rahul', lastName: 'Q.', country: 'Australia', continent: 'Australia', age: 65, language: 'PHP' },
];
const checkAllContinent = (arr = []) => {
const all = ['Africa', 'South America', 'North America', 'Europe', 'Asia', 'Australia'];
const listed = arr.map(obj => {
return obj.continent;
});
for(let i = 0; i
Output
false
How It Works
The function works by creating an array of all six continents, then removing each continent found in the input array. If all continents are removed (array length becomes 0), it returns true.
In this example, we only have 5 different continents in our data: Africa, South America, Asia, Europe, and Australia. We're missing North America, so the function returns false.
Alternative Approach Using Set
A cleaner solution uses a Set to collect unique continents:
const checkAllContinentSet = (arr = []) => {
const requiredContinents = ['Africa', 'South America', 'North America', 'Europe', 'Asia', 'Australia'];
const foundContinents = new Set(arr.map(obj => obj.continent));
return foundContinents.size === 6;
};
console.log(checkAllContinentSet(people));
false
Testing with All Continents
Let's test with data that includes all six continents:
const allContinentsPeople = [
{ firstName: 'John', continent: 'Africa' },
{ firstName: 'Jane', continent: 'South America' },
{ firstName: 'Bob', continent: 'North America' },
{ firstName: 'Alice', continent: 'Europe' },
{ firstName: 'Chen', continent: 'Asia' },
{ firstName: 'Mike', continent: 'Australia' }
];
console.log(checkAllContinent(allContinentsPeople));
true
Conclusion
This function effectively checks if all six continents are represented in an array of objects. The Set-based approach is more concise and readable than the splice method.
