Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codewars Coding Meetup #6 - Can they code in the same language?

Tags:

javascript

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;
}
like image 319
CocoFlade Avatar asked Aug 10 '26 21:08

CocoFlade


1 Answers

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))
like image 56
Maheer Ali Avatar answered Aug 13 '26 12:08

Maheer Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!