I want to get another array from the original array:

input example:

[[18, 20],[45, 2],[61, 12],[37, 6],[21, 21],[78, 9]] 

The conclusion should be the following: the first number - the age should be more than 55 , and the second - the work experience should be more than 7 .

 ["Open", "Open", "Senior", "Open", "Open", "Senior"] 

My code seems to solve, but I am ready to throw it into the furnace, the solution is not universal, I ask for help:

 var arr = [[18, 20],[45, 2],[61, 12],[37, 6],[21, 21],[78, 9]]; var arr2 = []; function openOrSenior(data){ if (Array.isArray(data)) { for (var i = 0; i < data.length; i++) { if (data[i][0] > 55 && data[i][1] > 7) { arr2.push("Senior"); } else { arr2.push("Open"); } } return arr2; } } console.log(openOrSenior(arr)); 

  1. How to get rid of global variables?
  2. How to check on an array universally?

    3 answers 3

    To map one collection of elements to another, use the map method.

     var arr = [ [18, 20], [45, 2], [61, 12], [37, 6], [21, 21], [78, 9] ]; var arr2 = []; function openOrSenior(data) { if (Array.isArray(data)) { return data.map(el => el[0] > 55 && el[1] > 7 ? "Senior" : "Open"); } } console.log(openOrSenior(arr)); 

    • good thank you - spectre_it pm
    1. you have a global variable only arr2 . In JavaScript, the scope is functional, so you just have to move the declaration of the variable inside the function.

    2. You can check for an array as follows:

     function isArray(someVar) { if( Object.prototype.toString.call( someVar ) === '[object Array]' ) { return true } else { return false }} 
       function openOrSenior(data){ function determineMembership(member){ return (member[0] >= 55 && member[1] > 7) ? 'Senior' : 'Open'; } return data.map(determineMembership); }