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 的内容为 [Bergamo, Milano, Pavia]

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 回答
1

我会用.map()and来做.filter()

var result = dataItaly.map(function(e) {
    return e[1] === region ? e[2] : null;
}).filter(function(e, i, a) {
    return e !== null && a.indexOf(e) === i;
});

注意:这些方法相当新,一些旧浏览器可能不支持它们。您应该使用垫片(从这里这里)来修复兼容性。

于 2013-05-13T09:21:58.127 回答
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 回答