使用 JavaScript 按顺序存储整数数量

javascriptweb developmentfront end technologyobject oriented programming

假设,我们有一个长字符串,表示像这样的数字 −

const str = '11222233344444445666';

我们需要编写一个 JavaScript 函数来接收一个这样的字符串。我们的函数应该返回一个对象,该对象应该为字符串中的每个唯一数字分配一个唯一的"id"属性,并分配另一个属性"count",用于存储数字在字符串中出现的次数。

因此,对于上述字符串,输出应如下所示 −

const output = {
   '1': { id: '1', displayed: 2 },
   '2': { id: '2', displayed: 4 },
   '3': { id: '3', displayed: 3 },
   '4': { id: '4', displayed: 7 },
   '5': { id: '5', displayed: 1 },
   '6': { id: '6', displayed: 3 }
};

示例

其代码为 −

const str = '11222233344444445666';
const countNumberFrequency = str => {
   const map = {};
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(map.hasOwnProperty(el)){
         map[el]['displayed']++;
      }else{
         map[el] = {
            id: el,
            displayed: 1
         };
      };
   };
   return map;
};
console.log(countNumberFrequency(str));

输出

控制台中的输出将是 −

{
   '1': { id: '1', displayed: 2 },
   '2': { id: '2', displayed: 4 },
   '3': { id: '3', displayed: 3 },
   '4': { id: '4', displayed: 7 },
   '5': { id: '5', displayed: 1 },
   '6': { id: '6', displayed: 3 }
}

相关文章


有用资源