Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping two dimensions array in Javascript

With an input of a 2 dimensions array I need to get as output an array with the elements in uppercase.

This is my try, but it doesn't works.

var cityColumn = [['avila'], ['burgos'], ['madrid'], ['sevilla']];
var cityRow = [['avila', 'avila', 'burgos', 'madrid', 'sevilla']];
var cityCell = [['sevilla']];


console.log(cityRow);
function upperCaseArray(myArray) {
  var upperized = myArray.map(function(city){
    console.log(typeof city);
    return city.toUpperCase();
  });
  return upperized;
}

console.log(upperCaseArray(cityColumn));
console.log(upperCaseArray(cityRow));
console.log(upperCaseArray(cityCell));
// output desired:
// [['AVILA], ['BURGOS'], ['MADRID'], ['SEVILLA']]
// [['AVILA, 'AVILA', 'BURGOS', 'MADRID', SEVILLA']]
// [['SEVILLA']]

Note: thesee inputs are that I've get from a Google Sheet range SpreadsheetApp.getActiveSpreadsheet().getSelection().getActiveRange().getValues(). I'm starting coding Google Apps Script.

like image 937
Trimax Avatar asked May 20 '26 17:05

Trimax


2 Answers

Because your strings are nested inside arrays which are inside arrays themselves, you need two .maps:

var cityColumn = [['avila'], ['burgos'], ['madrid'], ['sevilla']];
var cityRow = [['avila', 'avila', 'burgos', 'madrid', 'sevilla']];
var cityCell = [['sevilla']];
function upperCaseArray(arr) {
  return arr.map(function(subarr) {
    return subarr.map(function(str) {
      return str.toUpperCase();
    });
  });
}
console.log(upperCaseArray(cityColumn));
console.log(upperCaseArray(cityRow));
console.log(upperCaseArray(cityCell));
like image 199
CertainPerformance Avatar answered May 23 '26 06:05

CertainPerformance


var cityColumn = [['avila'], ['burgos'], ['madrid'], ['sevilla']];
var cityRow = [['avila, avila, burgos, madrid, sevilla']];
var cityCell = [['sevilla']];


console.log(cityRow);
function upperCaseArray(arr) {
  return arr.map(a => a.map(item => item.toUpperCase()));
  }

console.log(upperCaseArray(cityColumn));
console.log(upperCaseArray(cityRow));
console.log(upperCaseArray(cityCell));
like image 41
pgs Avatar answered May 23 '26 05:05

pgs



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!