user7575848
user7575848

Reputation:

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" ]

Upvotes: 0

Views: 645

Answers (3)

shae128
shae128

Reputation: 11

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) 

Upvotes: 0

Mohammad Usman
Mohammad Usman

Reputation: 39362

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));

Upvotes: 1

Sebastian Kaczmarek
Sebastian Kaczmarek

Reputation: 8515

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);

Upvotes: 2

Related Questions