How to prevent automatic sort of Object numeric property?

后端 未结 10 1259
醉酒成梦
醉酒成梦 2020-12-03 20:57

Why I met this problem: I tried to solve an algorithm problem and I need to return the number which appeared most of the times in an array. Like [5,4,3,2,1,1] should return

10条回答
  •  执笔经年
    2020-12-03 21:35

    The simplest and the best way to preserve the order of the keys in the array obtained by Object.keys() is to manipulate the Object keys a little bit.

    insert a "_" in front of every key name. then run the following code!

    myObject = {
      _a: 1,
      _1: 2,
      _2: 3
    }
    
    const myObjectRawKeysArray = Object.keys(myObject); 
    console.log(myObjectRawKeysArray)
    //["_a", "_1", "_2"]
    
    const myDesiredKeysArray = myObjectRawKeysArray.map(rawKey => {return rawKey.slice(1)}); 
    console.log(myDesiredKeysArray)
    //["a", "1", "2"]

    You get the desired order in the array with just a few lines of code. hApPy CoDiNg :)

提交回复
热议问题