Let’s say I have an array as follows:
[100,2,3,4,200,35,42,300,4,4,4,6,7,400,2]
And I want to create a map, like so:
{
{ key: 100,
value: 2
},
{ key: 100,
value: 3
}
{ key: 100,
value: 4
},
{ key: 200,
value: 35
},
{ key: 200,
value: 42
},
{ key: 300,
value: 4
},
{ key: 300,
value: 4
},
{ key: 300,
value: 4
},
{ key: 300,
value: 6
},
{ key: 300,
value: 7
},
{ key: 400,
value: 2
},
}
All the values in the bigger array are objects which have one or more fields.
I simulated the values with only one field using numbers 100, 200, 300, 400. You can call them flags. The rest of them being values with more than 1 field, of course.
My goal is to create map elements using the current flag with the items that follow it. For flag 300, the following elements are 4,4,4,6,7.
Here is what I tried:
let flagAndFollowingValues = new Map();
let j=0;
let followingElementsArray = [];
console.log(itemsToBeCheckedArray[j]);
for(let i=0; i<bigArray.length; i++){
if(Object.keys(bigArray[i]).length > 1)
{
followingElementsArray.push(bigArray[i]);
}else if(Object.keys(bigArray[i]).length === 1){
if(i===0){
j++;
flagAndFollowingValues.set(itemsToBeCheckedArray[j], followingElementsArray);
followingElementsArray=[];
}else{
flagAndFollowingValues.set(itemsToBeCheckedArray[j], followingElementsArray);
followingElementsArray=[];
}
}
}
6
Answers
First create a map logic, then filter out false entries:
I guess the code is self-explanatory. Just iterate the array and either get a new key or add a value to the current key.
You can reduce the data by adding new groups to the end of the resulting array.
Your proposed structure is useless, what you probably want is a map like
etc
Another
reduce()
option using a single flag instead of if/else/map’s100
, setflag
to that valueflag
askey
and the current value as thevalue
.If your flag is a multiple of 100, in that case it will work