Search code examples
javascriptjavascript-objects

why my object is sorting it's dynamic value when loop


I have this function that assigns dynamic key to initialized object

function meanCluster(clusters) {
   let initialized = {};

   clusters.forEach(mean => {
      initialized[mean] = [];
   })

   return initialized;
}

and I have these data

const OneDimensionPoint = [22, 9, 12, 15, 10, 27, 35, 18, 36, 11]

now I want to assign element 22, 9, and 12 as the key to my initialized variable inside my meanCluster function and to do that my approach is this code below.

let mean = [OneDimensionPoint[0], OneDimensionPoint[1], OneDimensionPoint[2]]

meanCluster(mean)

when I console.log(meanCluster(mean)) the result is this

{9: Array(0), 12: Array(0), 22: Array(0)}

I get 9, 12, 22 as the key instead of 22, 9, 12

my object is sorted, and I don't want. I also want to keep it as Number and not string.

can someone tell me why?


Solution

  • You can use a ES6 MAP:

    const OneDimensionPoint = [22, 9, 12, 15, 10, 27, 35, 18, 36, 11] ;
    let mean = [OneDimensionPoint[0], OneDimensionPoint[1], OneDimensionPoint[2]];
    
    console.log(
        mean.reduce((r,i)=>{
            r.set(i,[])
            return r;
        }, new Map())
    )