I have an array of objects in the following format:
var values = [
{
position: 6,
},
{
position: 4.5,
},
{
position: 2,
},
{
position: 7.5,
},
{
position: 2,
},
{
position: 5,
},
{
position: 3.5,
},
];
I want to change the key "position" value into the index of the object in the array. If any key value has a .5 decimal, I need to add the value before that index and continue assigning positions to the data above accordingly. The desired output should be as follows:
var values = [
{
level: 1,
},
{
level: 1.5,
},
{
level: 2,
},
{
level: 2.5,
},
{
level: 3,
},
{
level: 4,
},
{
level: 4.5,
},
];
Below is the code written to achieve the desired output:
values = values.map((item, index) => {
return {
level: index + 1 - (item.position % 1 === 0.5 ? 0.5 : 0),
};
});
OUTPUT :- [{"level":1},{"level":1.5},{"level":3},{"level":3.5},{"level":5},{"level":6},{"level":6.5}]
However, the current implementation is not yielding the expected results.
Your assistance on this matter would be greatly appreciated.
Thank you in advance!