How to prevent automatic sort of Object numeric property?

后端 未结 10 1280
醉酒成梦
醉酒成梦 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:30

    1. you can use Map() in javascript ES6 which will keep the order of the keys insertion.

    2. just trying to solve your problem in an alternative solution, recently like to practise leetcode-like question

    function solution(arr) {
      const obj = {};
      const record = {
        value: null,
        count: 0
      };
    
      for (let i = 0; i < arr.length; i++) {
        let current = arr[i];
        if (!obj[current]) {
          obj[current] = 0;
        }
    
        obj[current]++;
    
        if (obj[current] > record.count) {
          record.value = current;
          record.count = obj[current];
        }
      }
    
      console.log("mode number: ", record.value);
      console.log("mode number count: ", record.count);
    }
    

提交回复
热议问题