1

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?

LVC
  • 51
  • 2
  • 7
  • What are you doing that requires them to be in a different order? Object entries are stored in alphabetical/ascending order. Also object keys are always strings. – Axekan Nov 22 '22 at 17:20
  • it is needed for future calculations – LVC Nov 22 '22 at 17:24
  • Use an array if order is important. – Barmar Nov 22 '22 at 17:25
  • You could also use a `Map`. It maintains insertion order, without treating numeric keys specially. – Barmar Nov 22 '22 at 17:25
  • @Axekan Numeric keys are in numeric order, non-numeric keys are in insertion order. Nothing is in lexicographic order in objects. – Barmar Nov 22 '22 at 17:26
  • Does this answer your question? [Does JavaScript guarantee object property order?](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – damonholden Nov 22 '22 at 17:46

1 Answers1

0

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())
)
Vahid Alimohamadi
  • 4,900
  • 2
  • 22
  • 37