在对象中查找最大元素及其键 - React native

我首先必须告诉我,我浏览了此处的网站以找到答案,但我做不到。


我有一个包含键(服务名称)和值(计数器)的对象,我只想从该对象中提取最大和最小值及其键。


一个例子:


Object {

  "Learn JavaScript": 3, //Max

  "Learn React": 2, //Ignore

  "manicure": 1, //Min

}

然后我想创建一个对象数组,这些对象将按降序排列


我用来显示上层结果的代码:


 const arrayofServices  = services; //services => state the holding the services

          const servicesCounter = arrayofServices.reduce((counterObj, service) => {

            if (counterObj.hasOwnProperty(service)) {

              counterObj[service] += 1;

              return counterObj;

          }

          

            return {

              ...counterObj,

              [service]: 1

            };

          }, {});

          console.log("Service Counter in =>" ,servicesCounter);

有什么建议么?


料青山看我应如是
浏览 139回答 2
2回答

慕神8447489

再试一次 :)const obj = {"Learn JavaScript": 3, "Learn React": 2, "manicure": 1};function MinMaxFromObj(obj) {  const min = Math.min(...Object.values(obj));  const max = Math.max(...Object.values(obj));  const minKey = Object.entries(obj).find(([key, value]) =>   value === min ? key : null);  const maxKey = Object.entries(obj).find(([key, value]) =>   value === max ? key : null);  return [Object.fromEntries([minKey]), Object.fromEntries([maxKey])];} console.log(MinMaxFromObj(obj));

缥缈止盈

这是一种可以帮助您解决问题的方法:const minMaxEntry = (object) => {&nbsp; let minKey;&nbsp; let minValue = Infinity;&nbsp; let maxKey;&nbsp; let maxValue = -Infinity;&nbsp; for (const key in object) {&nbsp; &nbsp; if (object[key] < minValue) {&nbsp; &nbsp; &nbsp; minKey = key;&nbsp; &nbsp; &nbsp; minValue = object[key];&nbsp; &nbsp; }&nbsp; &nbsp; if (object[key] > maxValue) {&nbsp; &nbsp; &nbsp; maxKey = key;&nbsp; &nbsp; &nbsp; maxValue = object[key];&nbsp; &nbsp; }&nbsp; }&nbsp; const minEntry = { [minKey]: minValue };&nbsp; const maxEntry = { [maxKey]: maxValue };&nbsp; return [minEntry, maxEntry];};// --- //const object = {&nbsp; "Learn JavaScript": 3,&nbsp; "Learn React": 2,&nbsp; "manicure": 1,};const [minEntry, maxEntry] = minMaxEntry(object);console.log('Min Entry =>', minEntry);// { "manicure": 1 }console.log('Max Entry =>', maxEntry);// { "Learn JavaScript": 3 }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript