为了解决这个问题,我一直在转动轮子太久了,我已经准备好将计算机扔到窗外了。我如何减少这个数组:
const array = [
{'location': "Plovdiv", 'department': "Finance"},
{'location': "Plovdiv", 'department': "Client & Employee Support"},
{'location': "Plovdiv", 'department': "Client & Employee Support"},
{'location': "London", 'department': "Engineering"},
{'location': "London", 'department': "Engineering"},
{'location': "Plovdiv", 'department': "Engineering"}
];
对此:
{'location': "Plovdiv", 'department': ["Finance", "Client & Employee Support", "Engineering"]},
{'location': "London", 'department': ["Engineering"]},
我的目标是删除具有位置的对象中的重复数组,并将它们合并为单个键。其中每个键都有对应的部门列表。
编辑:我终于设法用普通ol'JS弄清楚了,但是它笨重,并且具有很多循环,我可以用更现代的方法来消除。
let locArray = [];
let newGrouping = [];
// For each location
for (let i = 0; i < locations.length; i += 1) {
// Check to see if the current locations is in the new locArray
if (locArray.indexOf(locations[i].location) === -1) {
// Get in there!
locArray.push(locations[i].location);
}
}
// Loop through the new set of unique locations
for (let i = 0; i < locArray.length; i += 1) {
let depArray = [];
// Loop through our original locations array
for (let j = 0; j < locations.length; j += 1) {
// Check to see if the current unique location matches the current location
// AND make sure that it's not already in depArray
if (locArray[i] === locations[j].location && depArray.indexOf(locations[j].department) === -1) {
// Get in there!
depArray.push(locations[j].department);
}
}
// Push our current unique location and its unique departments into a new object
newGrouping.push({
'location': locArray[i],
'departments': depArray
});
}
答案 0 :(得分:2)
使用Set
和map
我们要唯一地键入location
来执行此操作,我们使用Set
来确保唯一性。
// Notice we use the map function to pull just location.
new Set(array.map(({ location }) => location))
但是现在我们需要迭代那些唯一的键并重建数组。
因此,我们将Set
加载到Array
const unique = new Array(...new Set(array.map(({ location }) => location)))
现在我们有了一个array
唯一的location
,从这里我们可以使用map函数来构建所需的array
输出。
请注意,在构建array
的最后object
时,如何使用原始数组的department
和filter
对map
参数进行补水。
[Unique Location Array].map(location => ({
location, // ES6 the property name it is inferred
department: array.filter(({ location: l}) => location === l)
.map(({ department }) => department)
}));
const array = [
{'location': "Plovdiv", 'department': "Finance"},
{'location': "Plovdiv", 'department': "Client & Employee Support"},
{'location': "Plovdiv", 'department': "Client & Employee Support"},
{'location': "London", 'department': "Engineering"},
{'location': "London", 'department': "Engineering"},
{'location': "Plovdiv", 'department': "Engineering"}
];
const unique = new Array(...new Set(array.map(({ location }) => location)))
.map(location => ({
location,
department: array.filter(({ location: l}) => location === l)
.map(({ department }) => department)
}));
console.log(unique);