如何将具有相似值的map和push键迭代到同一数组中



我有一个结构如下的javascript映射:

let map = {3 => 1,
15 => 2,
0 => 2,
8 => 3,
9 => 3}

我需要接收键的数组,并且具有类似值的键应该在同一数组中。

[[3], [15,0],[8,9]]

这就是我尝试过的:

let answers = [];
let currentVal = 1;
map.forEach((value, key)=>{
let subArr = [];
if(value === currentVal){
subArr.push(key);
answers.push(subArr);
currentVal++;
}
});

return answers;

并返回[[3], [15], [8]]

出于可读性的原因,我假设您的地图是一个对象,而不是地图,但如果您在那里使用map,您可以更改方法来获取元素,但主要思想如下:

const data = {
3: 1,
15: 2,
0: 2,
8: 3,
9: 3
};
const customData = Object.entries(data).reduce((acc, [key, value]) => {
if (value in acc) {
acc[value].push(key);
} else {
acc[value] = [key];
}
return acc;
}, {});
const finalArray = Object.values(customData);
console.log(finalArray);

使用Map()编辑示例:

const data = new Map([
[3, 1],
[15, 2],
[0, 2],
[8, 3],
[9, 3]
]);
const customData = Array.from(data).reduce((acc, [key, value]) => {
if (value in acc) {
acc[value].push(key);
} else {
acc[value] = [key];
}
return acc;
}, {});
const finalArray = Object.values(customData);
console.log(finalArray);

您可以使用Object.entries销毁key, value,但我将它们的位置更改为value, key,以匹配OP:提供的数据结构图

let map = { 3: 1, 15: 2, 0: 2, 8: 3, 9: 3 };
const arr = [];
for (const [value, key] of Object.entries(map)) {
if (arr[key]) {
arr[key].push(value);
} else {
arr[key] = [value];
}
}
console.log(arr.filter(Boolean)); // [[3], [15,0],[8,9]]

注意arr.filter(Boolean)从数组中删除错误(空)值,因为索引0中没有数组!

您的映射不是有效的映射。因此,我使用Map实例来创建它。您可以查看Map Object的官方文档。

实时演示

// Creating a map object by using Map instance
const map = new Map();
// Setting the key, values in map object.
map.set(3, 1)
map.set(15, 2)
map.set(0, 2)
map.set(8, 3)
map.set(9, 3)
// Declaring an empty array which will store the result.
const arr = [];
// Iterate over a map object and assign the keys of map object into an 'arr'.
for (const [key, value] of map) {
(arr[value]) ? arr[value].push(key) : arr[value] = [key];
}
// Output
console.log(arr.filter(Boolean));

最新更新