2

次のような多次元配列から配列を作成したいと思います。

var dataItaly = [
/*Town       Region   City*/
  ["Castelspina","Piemonte","Alessandria"  ],
  ["Cavatore","Piemonte","Alessandria"  ],
  ["Cella Monte","Piemonte","Alessandria"  ],
  ["Cereseto","Piemonte","Alessandria"  ],
  ["Cantarana","Piemonte","Asti"  ],
  ["Capriglio","Piemonte","Asti"  ],
  ["Casorzo","Piemonte","Asti"  ],
  ["Albino","Lombardia","Bergamo"  ],
  ["Algua","Lombardia","Bergamo"  ],
  ["Abbiategrasso","Lombardia","Milano"  ],
  ["Agrate Brianza","Lombardia","Milano"  ],
  ["Aicurzio","Lombardia","Milano"  ],
  ["Almese","Piemonte","Torino"  ],
  ["Alpette","Piemonte","Torino"  ],
  ["Alpignano","Piemonte","Torino"  ],
  ["Andezeno","Piemonte","Torino"  ],
  ["Albonese","Lombardia","Pavia"  ],
  ["Albuzzano","Lombardia","Pavia"  ],
  ["Arena Po","Lombardia","Pavia"  ],
  ["Badia Pavese","Lombardia","Pavia"  ]
];

これが私の出発点です...

var region = "Piemonte"
// array must appear the city of "Piemonte"

function createArrayCity (dataItaly, region) {
var arrayList;
for (i = 0; i <dataItaly.length i) {
  if the region === [1] {
    arrayList [2]. append;
return arrayList;
}
}
}

この内容は、arrayList [Alessandria、Torino、Asti] でなければなりません。var region = "Lombardia" の場合、arrayList の内容は [ベルガモ、ミラノ、パビア] です。

4

3 に答える 3

1

concat を使用して配列をマージできます。

var dataItaly = [
  ["Castelspina","Piemonte","Alessandria"  ],
  ["Cavatore","Piemonte","Alessandria"  ],
  ["Cella Monte","Piemonte","Alessandria"  ],
  ["Arena Po","Lombardia","Pavia"  ],
  ["Badia Pavese","Lombardia","Pavia"  ]
];
var merged = [];
merged = merged.concat.apply(merged, dataItaly);

重複を削除するには(必要な場合)、次のようにします。

merged = merged.filter (function (v, i, a) { return a.indexOf (v) == i });
于 2013-05-13T09:18:59.510 に答える
0

試す

function createArrayCity (dataItaly, region) {
    var arrayList = [];
    for (i = 0; i <dataItaly.length; i++) {
        if (dataItaly[i][1] === region && indexOf(arrayList, dataItaly[i][2]) == -1) {
            arrayList.push(dataItaly[i][2])
        }
    }
    return arrayList;
}

function indexOf(array, obj){
    if(typeof array.indexOf == 'function'){
        return array.indexOf(obj);
    }
    for (i = 0; i <array.length; i++) {
        if(array[i] == obj){
            return i;
        }
    }
    return -1;
}


console.log(createArrayCity(dataItaly, 'Lombardia'))

デモ:フィドル

于 2013-05-13T09:28:27.710 に答える