假设我在javascript 中有这个数组
ar = ['C241C12A-45FD-40FF-B26E-B879107E584D||20',
'AB1BB99D-4396-415A-A5D8-1BEF3E0149CE||33',
'ADE54113-53D1-4F26-A01C-48EBE37E3CE8||85',
'DB500FD1-5988-4202-A4AA-727AC29AC67A||85',
'8A8EAB5A-E0D2-4AA8-96A0-42686FF5EB0C||10',
'50C29E8A-16C7-4FC2-A186-C3D65F23C627||200',
'70C79BBB-14C7-4F34-346B-CSSSDFVFZZZ7||200'
];
有什么方法可以得到这样的阵列吗
newarray1 = [
'ADE54113-53D1-4F26-A01C-48EBE37E3CE8||85',
'DB500FD1-5988-4202-A4AA-727AC29AC67A||85'
];
newarray2 = [
'50C29E8A-16C7-4FC2-A186-C3D65F23C627||200',
'70C79BBB-14C7-4F34-346B-CSSSDFVFZZZ7||200'
];
重复管道符号后的值,获取该值并基于形成一个新数组
var arraysByKey = {};
for (var i=0; i<ar.length; i++) {
var key = ar[i].split("||")[1];
if (key in arraysByKey)
arraysByKey[key].push( ar[i] );
else
arraysByKey[key] = [ ar[i] ];
}
结果(arraysByKey
(将如下所示:
{
"10": [
"8A8EAB5A-E0D2-4AA8-96A0-42686FF5EB0C||10"
],
"20": [
"C241C12A-45FD-40FF-B26E-B879107E584D||20"
],
"33": [
"AB1BB99D-4396-415A-A5D8-1BEF3E0149CE||33"
],
"85": [
"ADE54113-53D1-4F26-A01C-48EBE37E3CE8||85",
"DB500FD1-5988-4202-A4AA-727AC29AC67A||85"
],
"200": [
"50C29E8A-16C7-4FC2-A186-C3D65F23C627||200",
"70C79BBB-14C7-4F34-346B-CSSSDFVFZZZ7||200"
]
}
如果您只想要存在"重复值"的数组,只需过滤结果:
for (var key in arraysByKey)
if (arraysByKey[key].length < 2)
delete arraysByKey[key];
这不是最优雅的解决方案,但它将为您提供所需数组的对象。
dupecheck = {};
dupes = {};
$.each(ar, function () {
var num = this.split('||')[1];
if (typeof dupecheck[num] !== 'undefined') {
if (typeof dupes[num] === 'undefined') {
dupes[num] = [];
dupes[num].push(dupecheck[num]);
}
dupes[num].push(this);
}
dupecheck[num] = this;
});
http://jsfiddle.net/38wme/
var keyArray = {};
for ( var counter = 0; counter < ar.length; counter++)
{
var arValue = ar[ counter ];
var intVal = ar.split("||")[1];
if ( keyArray[ intVal ] == null || keyArray[ intVal ] == undefined )
{
keyArray[ intVal ] = new Array();
}
keyArray[ intVal ].push( arValue );
}
filterDuplicates();
function filterDuplicates( keyArray )
{
for ( key in keyArray )
{
keyArray[key] = keyArray[key].filter(function(elem, pos, self) {
return self.indexOf(elem) == pos;
}
}
return keyArray();
)
}
现在,在"keyArray"对象的每个索引值中都有一个数组