Отображение двух измерений массива в Javascript - PullRequest
0 голосов
/ 07 ноября 2018

При вводе массива 2 измерений мне нужно получить в качестве вывода массив с элементами в верхнем регистре.

Это моя попытка, но она не работает.

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']]

Примечание. Эти данные получены из диапазона Google Sheet SpreadsheetApp.getActiveSpreadsheet().getSelection().getActiveRange().getValues(). Я начинаю кодировать скрипт Google Apps.

Ответы [ 8 ]

0 голосов
/ 07 ноября 2018

Вы можете использовать map рекурсивно.

function toUpper(arr){
  if(arr.map){
   return arr.map(toUpper);
  } else {
   return arr.toUpperCase();
  }
}

Глубина рекурсии для двумерного массива составляет 2. GAS поддерживает до 1000.

0 голосов
/ 07 ноября 2018

Мне пришлось добавить одинарные кавычки в строки.

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));
0 голосов
/ 07 ноября 2018

Вы можете join() массив сделать массив в виде строки. Тогда заглавная строка. Наконец split() их снова из массива.

Изменить

return city.toUpperCase();

К

return city.join(',').toUpperCase().split(',');

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

function upperCaseArray(myArray) {
  var upperized = myArray.map(function(city){
    return city.join(',').toUpperCase().split(',');
  });
  return upperized;
}

console.log(upperCaseArray(cityColumn));
console.log(upperCaseArray(cityRow));
console.log(upperCaseArray(cityCell));
0 голосов
/ 07 ноября 2018

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));
0 голосов
/ 07 ноября 2018

Прежде всего, ваши элементы в массивах должны быть заключены в кавычки " или ', чтобы пометить их как строки, в противном случае интерпретатор увидит их как неопределенные переменные.

Вы можете использовать функцию map, чтобы применить функцию ко всем элементам в массиве. Но так как это двумерный массив, вам нужно применять его вложенным способом, как показано ниже:

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

function arrUpper(arr) {
    // o as in outer, and i as in inner
    return arr.map(o => o.map(i => i.toUpperCase()));
}

console.log(arrUpper(cityColumn));
console.log(arrUpper(cityRow));
console.log(arrUpper(cityCell));

выход

[["AVILA"], ["BURGOS"], ["MADRID"], ["SEVILLA"]]
[["AVILA", "AVILA", "BURGOS", "MADRID", "SEVILLA"]]
[["SEVILLA"]]
0 голосов
/ 07 ноября 2018
var cityColumn = [['avila'], ['burgos'], ['madrid'], ['sevilla']];
var cityRow = [['avila', 'avila', 'burgos', 'madrid', 'sevilla']];
var cityCell = [['sevilla']];

function parseData(input){
        return input.reduce(function(o,i){
            return i.reduce(function(oo,ii){
                oo.push(ii.toUpperCase());
                return oo;
            },[]);
        },[]);
    }

console.log(parseData(cityCell));
console.log(parseData(cityRow));
console.log(parseData(cityColumn));
0 голосов
/ 07 ноября 2018

Вы можете использовать .map() для создания массивов с заглавными строками:

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

function upperCase(arr) {
   return arr.map(function(a) {
      return a.map(function(s) { return s.toUpperCase(); });
   });
};

console.log(upperCase(cityColumn));
console.log(upperCase(cityRow));
console.log(upperCase(cityCell));
.as-console-wrapper { max-height: 100% !important; top: 0; }
0 голосов
/ 07 ноября 2018

Поскольку ваши строки вложены в массивы, которые находятся внутри самих массивов, вам необходимо two .map s:

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));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...