Why am I receiving varied results when trying to filter for distinct date values?

While attempting to filter unique dates, I've noticed that the output varies. In some cases, it works correctly, while in others, it does not. I'm having trouble figuring out what's causing this inconsistency. The filtering method below generally works well, but occasionally fails.

The goal is to extract all unique dates from both the RatingsDaily["2"] and RatingsDaily["4"] arrays.

// Data example:
const RatingsDaily = {
    "2": [
        {"2021-12-24": 3.21}, 
        {"2021-12-25": 3.19}, 
        {"2021-12-28": 3.29}, 
        {"2021-12-29": 3.24}, 
        {"2021-12-30": 3.38},
    ], 
    "4": [
        {"2021-12-24": 1.0}, 
        {"2021-12-25": 1.0}, 
        {"2021-12-26": 1.0}, 
        {"2022-01-27": 2.0}, 
        {"2022-01-03": 5.0}, 
        {"2022-01-05": 1.0},
    ]
}

// Current implementation:
let labels = []
let uniquelabel = []

for (let i = 0; i < RatingsDaily["2"].length; i++) {
    uniquelabel.push(Object.keys(RatingsDaily["2"][i]));
}

for (let i = 0; i < RatingsDaily["4"].length; i++) {
    uniquelabel.push(Object.keys(RatingsDaily["4"][i]));
}

const useFilter = arr => {
    return arr.filter((value, index, self) => {
        return self.indexOf(value) === index;
    });
};

const result = useFilter(uniquelabel);

console.log(result)

I would greatly appreciate any guidance on how to resolve this issue. Thank you for your assistance.

Answer №1

Consider utilizing a Set instead as it is specifically designed to store unique values. Additionally, it may be beneficial to dynamically handle the different types of ratings present, rather than hard-coding values like 2 and 4. You can achieve this by iterating over the keys in the RatingsDaily object. See an example implementation below:

const RatingsDaily = {"2": [{"2021-12-24": 3.21},{"2021-12-25": 3.19},{"2021-12-28": 3.29},{"2021-12-29": 3.24},{"2021-12-30": 3.38},], "4": [{"2021-12-24": 1.0},{"2021-12-25": 1.0},{"2021-12-26": 1.0},{"2022-01-27": 2.0},{"2022-01-03": 5.0},{"2022-01-05": 1.0}]}

const datesSet = new Set();
for (const rating of Object.keys(RatingsDaily)) {
    for (const dateObj of RatingsDaily[rating]) {
        datesSet.add(Object.keys(dateObj)[0]);
    }
}
const datesArr = Array.from(datesSet);
console.log(datesArr);

Answer №2

Here is a concise version:

const RatingsDaily = {"2": [{"2021-12-24": 3.21},{"2021-12-25": 3.19},{"2021-12-28": 3.29},{"2021-12-29": 3.24},{"2021-12-30": 3.38},], "4": [{"2021-12-24": 1.0},{"2021-12-25": 1.0},{"2021-12-26": 1.0},{"2022-01-27": 2.0},{"2022-01-03": 5.0},{"2022-01-05": 1.0}]}

const result = [...new Set( // ensures uniqueness
    Object.values(RatingsDaily).flat() // fetches all entries
    .map(Object.keys).flat() // retains only string dates
  )]

console.log(result);

Answer №3

The array uniquelabel consists of one-element sub-arrays. It seems like this may not be your intended structure; perhaps you were aiming for an array of strings (dates) instead of arrays. To rectify this, simply make two adjustments as suggested below.

Replace:

uniquelabel.push(Object.keys(RatingsDaily[n][i]));

With:

uniquelabel.push(...Object.keys(RatingsDaily[n][i]));

In essence, utilize the spread operator to insert a string into uniquelabel rather than an array.

DEMO

// Given data
const RatingsDaily = { "2": [ {"2021-12-24": 3.21}, {"2021-12-25": 3.19}, {"2021-12-28": 3.29}, {"2021-12-29": 3.24}, {"2021-12-30": 3.38}, ], "4": [ {"2021-12-24": 1.0}, {"2021-12-25": 1.0}, {"2021-12-26": 1.0}, {"2022-01-27": 2.0}, {"2022-01-03": 5.0}, {"2022-01-05": 1.0}, ] };

// Approach taken
let labels = []
let uniquelabel = []

for (let i = 0; i < RatingsDaily["2"].length; i++) {
    uniquelabel.push(...Object.keys(RatingsDaily["2"][i]));
}

for (let i = 0; i < RatingsDaily["4"].length; i++) {
    uniquelabel.push(...Object.keys(RatingsDaily["4"][i]));
}

const useFilter = arr => {
    return arr.filter((value, index, self) => {
        return self.indexOf(value) === index;
    });
};

const result = useFilter(uniquelabel);

console.log(result)

Answer №4

If you're looking for a solution, this snippet of code could be exactly what you need:

let uniqueLabels = [];

for(let i = 0; i < RatingsDaily[2].length; i++) {
    uniqueLabels.push(Object.keys(RatingsDaily[2][i])[0]);
}

for(let i = 0; i < RatingsDaily[4].length; i++) {
    uniqueLabels.push(Object.keys(RatingsDaily[4][i])[0]);
}

const filterDuplicates = (arr) => {
    return arr.sort().filter((value, index, self) => {
        return !index || value != self[index - 1];
    });
};

const finalResult = filterDuplicates(uniqueLabels);

console.log(finalResult);

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

When running Rollup, a syntax error occurs due to the use of the "import" syntax in an internal Rollup file using Javascript

I am working on a nodeJS/express application with a rollup bundler. My rollup configuration file defines a command in the package.json like this: "build": "env ROLLUP_OPTIONS='prod' rollup --config configs/rollup.config.js". However, when I run " ...

Consistent column heights within each row

I currently have Bootstrap implemented on my website and have integrated jQuery to adjust the height of each column to match the tallest one. However, the issue I am facing is that the height adjustment applies globally across the entire page, rather than ...

Once the vue-cli has deployed to the server, the server's requested image path is now located in /dist/ folder

Issue with Image Loading: While the demo successfully loads all resources and uploads images correctly, there is an issue where an extra /dist/ is being requested for image paths, resulting in a 404 error. Demo Link: Configuration of the Demo: vue.conf ...

Leveraging angular.forEach for JSON Iteration

In my app and controller, I am working on creating a "flow chart style" question and answer system. To keep track of the current question and answer, I am using variables like $scope.ActiveQuestion and an array named $scope.ActiveAnswers. I am struggling ...

Using Jquery to automatically populate an input field if the user already exists

I'm currently working on populating a form if the user input for name and firstname already exists in my database. However, I am facing an issue with my JavaScript program where it fails to check if the name and firstname combination already exists i ...

Merge JSON object information into tables, including column headings

I am currently facing a challenge in loading multiple JSON files into tables within different divs. Here is the structure of my JSON data: JSON file 1: [ { "id": 12345, "code": "final", "error": "", "data": [ ...

Removing a Child Object from a JSON Object in AngularJS

Encountering an error while attempting to remove a Child object Error Message: TypeError: ctrl.otsact.tests.splice is not a function HTML : <tr ng-repeat="act in ctrl.otsact.tests" ng-if="ctrl.editToggle"> <td><span ng-click="ctrl.r ...

The setInterval function is malfunctioning

If I have the following function: function check(){ alert("Welcome"); } window.onload = check(); setInterval("check();", 5000); However, it is not working properly. Oddly enough, when I refresh the page, it works as intended. How can I resolve this i ...

How to Use Express.js to Stream Assets (JS/CSS/images) from Amazon S3

After successfully launching my Node.js blog on AppFog, I have the idea of utilizing an Amazon S3 bucket to host and stream all my assets such as javascript, stylesheets, and images. I am now wondering how I can configure Express.js to properly serve thes ...

Controller function failing to trigger

I'm new to asking questions, so if I've made a mistake, please let me know. I've searched for an answer here but couldn't find one. Any help would be greatly appreciated. I'm attempting to load a list of "Countries" using a contro ...

Fill in input field based on choice from the drop-down menu - JavaScript

I am facing an issue where I cannot add text inside the text box based on the dropdown selection. For example, if I select option2 from the dropdown, the textbox should be populated with option2. (function() { 'use strict'; setInterva ...

I want to create a feature in Angular where a specific header becomes sticky based on the user's scroll position on the

When working with Angular, I am faced with the challenge of making a panel header sticky based on the user's scroll position on the page. I have identified two potential solutions for achieving this functionality. One involves using pure CSS with pos ...

Using Postman to transmit a JSON API object

I'm currently utilizing the JSONAPI Specification from Here is an example of the data I have: { "data": { "type": "tag", "id": "1", "attributes": { "name": "Test" } } } Is there a way to send a post request to the e ...

Verify whether a specific value exists in my React array; if it does, display a specific component

I need to display different components based on the following criteria: Whether the items contain a specific value And if all 10 items have that value const DisplayComponents = ({ data }: Props) => { const filteredItems = data.items?.filter( ( ...

Attempting to create an array using jQuery's :checked selector

In my table structure below, I have multiple rows with various data: <tr class="row"> <td class="row-checkbox-delete-row"> <input tabindex="-1" class="checkbox-delete-row" type="checkbox" /> </td> <td class="r ...

Creating a hierarchical JSON layout for constructing dual d3.js graphs side by side

I am currently struggling with navigating through a JSON structure that I created in order to generate side-by-side donut charts. I suspect that my structure is not ideal and would greatly appreciate any guidance. My inspiration comes from Mike Bostock&ap ...

Regular expression that detects a phone number which does not consist of a repetition of the same digit throughout

Looking for a regex pattern to match phone numbers that do not consist of the same number repeated throughout every part. Specifically, I need it to target 10-digit phone numbers in the format (123)123-1234. I have tried using this pattern, but it's ...

Implementing model synchronization on server initialization with Next.js and sequelize

When it comes to using Express with React on the backend, I'm accustomed to working in a server.js file to synchronize the database. However, I've recently started working with Next.js and noticed that there's no server.js file to sync the m ...

When utilizing the header slot in v-data-table, an empty header row is unexpectedly appearing

Having an issue with adding an extra empty row when using the header slot in v-data-table from Vuetify2. Check out the codepen here: https://codepen.io/satishvarada/pen/rNBjMjE?editors=1010 Vue.component('pivot-table',{ data:()=>({ ...

Utilize the table's checkboxes to select recipients for mail distribution

I am working with a database table structure like this: ID email After fetching data from the database, I display it in an html table: <?php $sql = $link->query("SELECT ..."); while($data = $sql->fetch_object){ ?> <table> < ...