Javascript array processing, the same put together
suppose there is an array like this
[
{eid: cat, name: aa},
{eid: cat, name: bb},
{eid: dog, name: cc},
{eid: cat, name: dd},
{eid: pig, name: ee},
{eid: cat, name: ff},
{eid: dog, name: gg}
]
I want to process the array, putting the same eid together
becomes
[
{eid: cat, name: aa},
{eid: cat, name: bb},
{eid: cat, name: dd},
{eid: cat, name: ff},
{eid: dog, name: cc},
{eid: dog, name: gg},
{eid: pig, name: ee}
]
is there a way to achieve this?
[
{eid: 'cat', name: 'aa'},
{eid: 'cat', name: 'bb'},
{eid: 'dog', name: 'cc'},
{eid: 'cat', name: 'dd'},
{eid: 'pig', name: 'ee'},
{eid: 'cat', name: 'ff'},
{eid: 'dog', name: 'gg'}
].sort((a, b) => {
return a.eid === b.eid ? 1 : -1
}).reverse()
the result is shown in figure
it is right to use the sort train of thought ~
but the comparison method of @ zollero uses = =
has a problem, but the result happens to be correct, so it is wrong to change the second item to be different from the first item.
adjust it slightly:
[
{eid: 'cat', name: 'aa'},
{eid: 'cat', name: 'bb'},
{eid: 'dog', name: 'cc'},
{eid: 'cat', name: 'dd'},
{eid: 'pig', name: 'ee'},
{eid: 'cat', name: 'ff'},
{eid: 'dog', name: 'gg'}
].sort((a, b) => {
return a.eid > b.eid ? 1 : -1
})
var data = [
{eid: 'cat', name: 'aa'},
{eid: 'cat', name: 'bb'},
{eid: 'dog', name: 'cc'},
{eid: 'cat', name: 'dd'},
{eid: 'pig', name: 'ee'},
{eid: 'cat', name: 'ff'},
{eid: 'dog', name: 'gg'}
]
function trans (data) {
let cache = {} // cacheeideidindices
let indices = [] // eid
data.forEach((item, i) => {
let eid = item.eid
let index = cache[eid]
if (index !== undefined) {
indices[index].push(i)
} else {
cache[eid] = indices.length
indices.push([i])
}
})
/**
* cache:{cat: 0, dog: 1, pig: 2}
* indices: [[0, 1, 3, 5], [2, 6], [4]]
* indices1eidcat
* indices2eiddog
* indices3eidpig
*/
let result = []
indices.forEach(item => {
item.forEach(index => {
result.push(data[index]) // indexdata[index]
})
})
return result
}
let result = trans(data)
console.log(result)
there is an ambiguity in your question, such as the following example:
var data = [
{eid: 'dog', name: 'aa'},
{eid: 'cat', name: 'bb'},
{eid: 'dog', name: 'cc'}
]
do you want to output 1:
[
{eid: 'dog', name: 'aa'},
{eid: 'dog', name: 'cc'},
{eid: 'cat', name: 'bb'}
]
still want to output 2:
[
{eid: 'cat', name: 'bb'},
{eid: 'dog', name: 'aa'},
{eid: 'dog', name: 'cc'}
]
output 1 is arranged in the order in which it appears, output 2 is arranged in alphabetical order, I give the function of output 1, if you want to output the results of 2, you can refer to the upstairs.