[英]How to iterate through map and push keys with similar values into the same array?
I've got javascript map with structure like this:我有这样结构的javascript地图:
let map = {3 => 1,
15 => 2,
0 => 2,
8 => 3,
9 => 3}
I need to receive the arrays of keys, and keys with similar values should be in the same array.我需要接收键的数组,具有相似值的键应该在同一个数组中。
[[3], [15,0],[8,9]]
This is what I've tried:这是我尝试过的:
let answers = [];
let currentVal = 1;
map.forEach((value, key)=>{
let subArr = [];
if(value === currentVal){
subArr.push(key);
answers.push(subArr);
currentVal++;
}
});
return answers;
And it returns [[3], [15], [8]]
它返回[[3], [15], [8]]
I assume your map is an object, not map for readability reasons, but if u are using Map there you can change methods to get elements but main idea you can see below:我假设您的地图是一个对象,而不是出于可读性原因的地图,但如果您在那里使用地图,您可以更改获取元素的方法,但您可以在下面看到主要思想:
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);
Edit with Map()
example:使用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);
You could use Object.entries
and destructuring key, value
but I change their place as value, key
to match the data structure map provided by OP :您可以使用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]]
NOTE arr.filter(Boolean)
to remove falsy (empty) values from array since index 0 have no array inside of it!注意arr.filter(Boolean)
从数组中删除虚假(空)值,因为索引0内部没有数组!
Your map is not a valid one.您的地图无效。 Hence, I am creating it by using Map
instance.因此,我使用Map
实例创建它。 You can have a look in this official documentation of Map Object
.您可以查看Map Object
的官方文档。
Live Demo :现场演示:
// 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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.