[{"1":"A"},{"2":"A"},{"3":"B"},{"4":"A"},{"5":"C"},{"6":"B"},{"7":"B"}]
這是一個數組,其中第一個元素是id,第二個元素是用戶。如果用戶是'A',那麼數組將是[1,2,4] 如果用戶是'B',那麼數組將會是[3,7]在javascript中過濾數組
在JavaScript中做到這一點?我需要使用地圖還是過濾方法?
[{"1":"A"},{"2":"A"},{"3":"B"},{"4":"A"},{"5":"C"},{"6":"B"},{"7":"B"}]
這是一個數組,其中第一個元素是id,第二個元素是用戶。如果用戶是'A',那麼數組將是[1,2,4] 如果用戶是'B',那麼數組將會是[3,7]在javascript中過濾數組
在JavaScript中做到這一點?我需要使用地圖還是過濾方法?
使用Array#filter
,String#split
和Array#map
方法。
var arr = ['1:A', '2:A', '3:B', '4:A', '5:C', '6:B', '7:B'];
// filter out array
var res = arr.filter(function(v) {
// split and check user is A
return v.split(':')[1].trim() == 'A'
}).map(function(v) {
// retrive the number part and parse
return Number(v.split(':')[0]);
});
console.log(res);
或者使用單Array#forEach
循環。
var arr = ['1:A', '2:A', '3:B', '4:A', '5:C', '6:B', '7:B'];
// initialize array to hold the result
var res = [];
// iterate over the array element
arr.forEach(function(v) {
// strint the string
var spl = v.split(':');
// check user is A
if (spl[1].trim() == 'A')
// if user is A parse and push value to result array
res.push(Number(spl[0]))
});
console.log(res);
UPDATE:如果它是那麼的對象使用Object.keys
和Array#map
方法。
var obj = {
1: 'A',
2: 'A',
3: 'B',
4: 'A',
5: 'C',
6: 'B',
7: 'B'
};
var res = Object.keys(obj) // get all object keys
// filter out keys array
.filter(function(k) {
// check the property value
return obj[k] == 'A';
// parse the result array if you want to convert
// into a Number array
}).map(Number);
console.log(res);
您可以通過用戶使用Array#reduce
和組所有項目。
var array = ['1:A', '2:A', '3:B', '4:A', '5:C', '6:B', '7:B'],
groups = array.reduce(function (r, a) {
var p = a.split(':');
r[p[1]] = r[p[1]] || [];
r[p[1]].push(p[0]);
return r;
}, Object.create(null));
console.log(groups);
是字符串? –
無效數組 – ricky
到目前爲止你做了什麼? –