简体   繁体   中英

Get specific data from array and put in other array

I have this result in javascript and i want to get data that has value more that 3 and i want to put in other array .

"availableDates": {
  "2020-01-24": 1,
  "2020-01-23": 3,
  "2020-01-22": 2,
  "2020-01-21": 1,
  "2020-01-25": 4,
  "2021-01-07": 1
}

I group here :

const formattedDate = x.reduce((acc,el) => {
  const date = el.split(" ")[0];
  acc[date] = (acc[date] || 0) + 1;
  return acc;
}, {});

now I want to put in other array all that date that has value more than 3 . For example

newarray = [ "2020-01-23", "2020-01-25" ]

Why don't use a simple .filter() over keys of "availableDates" :

 const grouped = { "availableDates": { "2020-01-24": 1, "2020-01-23": 3, "2020-01-22": 2, "2020-01-21": 1, "2020-01-25": 4, "2021-01-07": 1 } }; const newArray = Object.keys(grouped.availableDates).filter((key) => grouped.availableDates[key] >= 3); console.log(newArray);

You can simply use a for...in loop to iterate over object keys and filter them:

 const data = { "2020-01-24": 1, "2020-01-23": 3, "2020-01-22": 2, "2020-01-21": 1, "2020-01-25": 4, "2021-01-07": 1 }; const reducer = (obj, val) => { const result = []; for(key in obj) { if(obj[key] >= val) result.push(key); }; return result; }; console.log(reducer(data, 3));

You could have something like this. I write a complete bunch of the code to make you able to copy/past to test

var availableDates = new Array()
var availableDates =  {
        "2020-01-24": 1,
        "2020-01-23": 3,
        "2020-01-22": 2,
        "2020-01-21": 1,
        "2020-01-25": 4,
        "2021-01-07": 1
    }
var results = new Array();
 for (date in availableDates){
   if (availableDates[date] >= 3){
      results.push(date)    
  }
 }

 console.log(results) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM