Retrieve particular information from an array and transfer it to another array

In my JavaScript code, I have a result stored in an object named "availableDates". I am looking to extract the dates that have a value greater than 3 and place them into a new 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
}

Here's the grouping function I'm using:

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

Now, I need to populate another array with all the dates that have a value greater than 3. For example:

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

Answer №1

Is there a reason why you are not utilizing a simple .filter() method on the keys within the "availableDates" object?

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

Answer №2

To filter object keys, you can utilize a for...in loop for iteration:

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 filterKeys = (obj, val) => {
  const result = [];

  for(key in obj) {
    if(obj[key] >= val)
      result.push(key);
  };
  
  return result;
};

console.log(filterKeys(data, 3));

Answer №3

Here is a sample code snippet for you to try out. Feel free to copy and paste it into your editor:

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) 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps can I take to optimize this Java function for better performance?

I am in search of ways to optimize my function for better efficiency. Here is the current implementation: public boolean addAll(int i, Collection<? extends T> c) { for (T x : c) add(i++, x); return true; } public void add(int i, T x ...

Switching numbers in a two-dimensional array

I attempted to reverse the numbers within this 2D array, but I found myself unintentionally only reversing the first and last numbers. At this point, I have made some progress on it, yet I am uncertain about where my error lies and how to rectify it so th ...

Problem with Declaring Variables in VB6

It's been quite some time since I last worked with vb6. I used to declare variables like this: dim a,b,c as integer However, recently while working on a program that involved arrays, the declaration dim ar(10),i,a as integer gave me unexpected res ...

Having trouble retrieving the value from a textarea in HTML using CodeIgniter with AJAX and PHP

Having trouble fetching the value of your textarea in PHP from AJAX? It seems that when you try to retrieve the value from HTML to JavaScript using var content = $('textarea[name=post_content]').val(); console.log(content);, it displays the value ...

Having difficulties decoding a base64 string in JavaScript? Try using Linux's base64 command!

I have successfully extracted the base64 encoded header from a Playready DRM manifest. However, I am encountering an issue when trying to decode the string in Javascript using methods like atob. There seems to be a missing character square between each ex ...

In Ruby on Rails 3.2, each request attempts to access a URL with a timestamp format of /[timestamp]?_[timestamp

Wondering why every request in my Rails Production environment is hitting the same page with a timestamp appended to it. The headers indicate that it's expecting javascript. This extra request seems to be causing a delay in loading pages, as now each ...

Struggling with creating dynamic HTML div IDs

I am currently working on developing a feature that generates a new "panel" with dynamic content. However, I have encountered an issue where the newly created div does not receive the assigned id despite my explicit efforts to do so. The id is supposed to ...

Can automation software such as Selenium or Puppeteer be used to intercept and analyze HTTP requests?

While utilizing Selenium (or another automation software), I am interested in capturing all incoming HTTP requests. Specifically, I want to be able to access the data associated with these requests such as headers and responses when visiting a website: ht ...

Encountering a Cannot GET error when using Express routing with parameters:

I've encountered a "Cannot GET" error while attempting to use express routing with parameters for the first time, and I'm puzzled as to why. Everything was working smoothly until I installed lodash, and now nothing seems to work anymore. Here&a ...

Retrieving values from JSON using React

I've recently started learning React and have been exploring how to fetch and handle JSON data. For testing purposes, I'm using the following API: My goal is to console log the username when clicking on a username from the JSON data. How can I p ...

Does React JS set initial value after re-rendering its state?

Every time the state is updated, the function is triggered once more (please correct me if I am mistaken). And since the initial line of the App function sets the state, the values of data and setData will not revert to their defaults. For instance, i ...

Using jQuery, learn how to successfully call a selector from dynamic content

I am currently facing a challenge with a table that is generated server-side and then appended to the view page (client-side). Since the table is not directly included in the DOM, I am using the StickyTableHeaders jQuery plugin to create a sticky header fo ...

Activate HTML5 video playback one time only

How can I use a script to play an HTML5 video only once when an element is in viewport, and then pause it? When I start scrolling again, the video should resume playing. Any suggestions on how to trigger play just once? Script: jQuery.fn.isInViewport = fu ...

Issue encountered while generating dynamic Routes using the map function

When attempting to dynamically use Route from an array, I encounter an error. Warning: Incorrect casing is being used. Use PascalCase for React components, or lowercase for HTML elements. The elements I am utilizing are as follows: const steps = [ { ...

What is a method for generating a unique random number that appears only once?

I need a program that can generate up to 5 unique numbers between 0-4 without repeating any number. The program should stop after three attempts, ensuring that the random numbers generated are always different each time. My current code involves an array ...

Implement a bootstrap modal to pop up upon successful form validation using the formvalidation.io

Dealing with a form that can take a significant amount of time to submit due to posting data to multiple APIs is not uncommon. Normally, I display a message in a bootstrap modal asking the user to wait patiently without clicking the back button. This modal ...

Using ng-init to pass a JSON object

I'm attempting to pass a JSON Object to my application using ng-init and the stringify method, but I am encountering an error. Instead of working as expected, I am getting a Lexer error. Lexer Error: Unexpected next character at columns 8-8 [#] in ex ...

React: the value of this.props.item has not been defined

When attempting to pass an array from one component to another and then to a third component, the item is showing up as undefined. In my App.js file, I am trying to pass this.state.searchResults to the SearchResults component. import React from 'rea ...

Encountering an error while attempting to utilize the split function in browser.umd.js due to

Hey there, I seem to be encountering an issue that states: Cannot read properties of undefined (reading 'split'). I came across this error message in the console https://i.sstatic.net/3nICv.png Upon clicking the link to the error, it directs me ...

Expanding Java Classes and Replacing Methods with Multiple Parameters in ES4X/Graal

I am currently facing a challenge in my JavaScript project using ES4X/Graal, where I need to extend a Java class. This Java class has methods with overloaded parameters that I must override. While I understand how to call a specific Java method by specifyi ...