I'm starting very basic trying to approach this using for and if loops, rather than anything too advanced for myself. I am seeking a push in the right direction.
You will be given an array of objects (associative arrays in PHP) representing data about developers who have signed up to attend the next coding meetup that you are organising.
Your task is to return either:
true if all developers in the list code in the same language; or false otherwise. For example, given the following input array:
var list1 = [ { firstName: 'Daniel', lastName: 'J.', country: 'Aruba', continent: 'Americas', age: 42, language: 'JavaScript' }, { firstName: 'Kseniya', lastName: 'T.', country: 'Belarus', continent: 'Europe', age: 22, language: 'JavaScript' }, { firstName: 'Hanna', lastName: 'L.', country: 'Hungary', continent: 'Europe', age: 65, language: 'JavaScript' }, ];your function should return true.
My logic is that if every language in the array is equal to the very first one, then it should return true, as clearly they would all be the same, if not return false.
However when I run the code it returns only true and fails to return false, here is what I have:
function isSameLanguage(list) {
for (var i = 0; i < list.length; i++) {
if (list[i].language === list[0].language) {
return true;
}
}
return false;
}
In the simple language your codes means
if (list[i].language === list[0].language) {
return true;
}
The above part means that if list[i].language(any language) is equal to first element's language list[0].language then return true. So this is not what you want.
You want if any of the language list[i].language is not equal to first language list[0].language then return false
You should change condition from === to !== and then return false inside the loop
var list1 = [
{ firstName: 'Daniel', lastName: 'J.', country: 'Aruba', continent: 'Americas', age: 42, language: 'JavaScript' },
{ firstName: 'Kseniya', lastName: 'T.', country: 'Belarus', continent: 'Europe', age: 22, language: 'JavaScript' },
{ firstName: 'Hanna', lastName: 'L.', country: 'Hungary', continent: 'Europe', age: 65, language: 'JavaScript' },
];
function isSameLanguage(list) {
for (var i = 1; i < list.length; i++){
if (list[i].language !== list[0].language){
return false;
}
}
return true;
}
console.log(isSameLanguage(list1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With