Loop through an array of JavaScript objects, compare a specific value within each object with all others to ensure uniqueness, and then add the unique objects to a new array

What is a efficient method to iterate through a JavaScript array of objects, and within each object, verify the uniqueness of a specific value compared to all others before adding it to a new array.

Here is the sample array of objects:

const weatherArray = [
  {
    dt: 1526871600
    dt_txt: "2018-05-21 03:22:00"
  },
  {
    dt: 1526871600
    dt_txt: "2018-05-22 03:30:00"
  },
  {
    dt: 1526871600
    dt_txt: "2018-05-21 03:50:00"
  },
  {
    dt: 1526871600
    dt_txt: "2018-05-23 03:17:00"
  },
  {
    dt: 1526871600
    dt_txt: "2018-05-23 03:23:00"
  }
]

The goal is to examine each object and only add those with unique dt_txt values (date portion only, excluding time) to a new array.

Attempted solution provided below with annotations:

var uniqueDays = []
function getDays(weatherArray) {
  // Add the first value to new array for comparison
  uniqueDays.push(weatherArray[0])
  // Extract date portion from dt_txt for comparison
  let firstDayString = weatherArray[0].dt_txt.split(" ")[0]

  weatherArray.map((day) => {
    let dayString = day.dt_txt.split(" ")[0]

    uniqueDays.map((uniqueDay, index) => {
      // Extract date portion from new array items
      let unqiueDayString = uniqueDay.dt_txt.split(" ")[0]

      // Skip if the value already exists
      if (unqiueDayString == dayString) {
        console.log('duplicate');
      } else {
        // Otherwise add to new array (issue identified)
        uniqueDays.push(day)
      }
    })
  })

  return uniqueDays
}

The recursion issue arises from pushing within the same map function. Seeking advice on better strategies or solutions for this problem. Any suggestions would be greatly appreciated as I've been grappling with this challenge for some time.

Answer №1

const weatherArray = [
  {
    dt: 1526871600,
    dt_txt: "2018-05-21 03:22:00"
  },
  {
    dt: 1526871600,
    dt_txt: "2018-05-22 03:30:00"
  },
  {
    dt: 1526871600,
    dt_txt: "2018-05-21 03:50:00"
  },
  {
    dt: 1526871600,
    dt_txt: "2018-05-23 03:17:00"
  },
  {
    dt: 1526871600,
    dt_txt: "2018-05-23 03:23:00"
  }
]

const seen = {};
const res = weatherArray.filter(function(dt){
  const date = dt.dt_txt.substring(0, 10);
  if (!seen[date]) {
    seen[date] = true;
    return true;
  }
});

console.log(res);

It's important to note that the method used here for parsing dates may not be optimal for all scenarios as it assumes a specific format (YYYY-MM-DD) and utilizes substring. Other methods like split or regular expressions could be considered depending on requirements.

The issue in your original code lies in looping over uniqueDays while also adding elements to it within the loop. This can lead to unexpected behavior and inefficiency.

A more efficient approach is demonstrated in the solution above where dates are parsed only once per item, resulting in faster processing time compared to repeated parsing.

In your initial code snippet, the usage of map instead of

forEach</code led to generating an array of undefined values which may not have been the intended outcome.</p>

<p>If date parsing is not required, alternatives like <code>indexOf
or findIndex can be utilized for checking array contents efficiently.

Overall, searching for properties in objects tends to be faster than traversing arrays due to the hash map nature of objects versus linear search in arrays.

Kudos to @CertainPerformance for their elegant solution as well, though it involves additional iteration when converting object values back to an array using Object.values, potentially impacting performance with large result sets.

Answer №2

If you want to organize items in an array, you can use the .reduce method to group each unique date into an object with indexes based on dates and then extract the values from that object:

const weatherArray=[{dt:1526871600,dt_txt:"2018-05-21 03:22:00"},{dt:1526871600,dt_txt:"2018-05-22 03:30:00"},{dt:1526871600,dt_txt:"2018-05-21 03:50:00"},{dt:1526871600,dt_txt:"2018-05-23 03:17:00"},{dt:1526871600,dt_txt:"2018-05-23 03:23:00"}];

const output = 
  Object.values(
    weatherArray.reduce((accum, obj) => {
      const date = obj.dt_txt.slice(0, 10);
      if (!accum[date]) accum[date] = obj;
      return accum;
    }, {})
  );
console.log(output);

Answer №3

 const uniqueDatesArray = [];

datesArray.forEach(date => {
  const day = date.dt_txt.split(' ')[0];

  if(!uniqueDatesArray.some((x) => x.dt_txt.split(' ')[0] === day)){
    uniqueDatesArray.push(date);
  }
})

In basic terms, the algorithm works as follows:

  • Iterate through datesArray
  • For each date, check if it exists in the unique array
    • If not found, add this date object to the unique array
    • Otherwise, do nothing

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 is the best way to stylize a date using Bootstrap-datepicker?

While this topic is well-known, I have a slightly more complex question regarding it. I have gone through the documentation here. My goal is to display the date in French format (dd/mm/yyyy) and save the value in US format (yyyy-mm-dd). Additionally, I nee ...

Before I press enter, what kind of function is evaluated by the Node.JS REPL?

It's interesting how in the Node.JS REPL, the result of the current expression sometimes gets evaluated before hitting enter, which raises questions. I find it puzzling: How does Node.JS determine if I intended to evaluate it or not? Simple calculati ...

Tailored NodeJS compilation incorporating JavaScript modules

Can NodeJS be built together with specific JavaScript modules? I am aware that for native modules, node-gyp can assist with this, but I am unsure about how to accomplish this with JavaScript modules. My goal is to use a custom application without needing t ...

What is the best way to attach a Label to a THREE.Mesh object?

I'm looking to show the name of a Three.js Three.Mesh as a label when hovering over the mesh. Does anyone know how to achieve this in Three.js? Could someone provide an example code snippet for this? ...

Transferring data from one pandas series list to another using specific indexes

I am working with a pandas data frame that contains two series. Each series consists of 2D arrays - series 'a' has sub-arrays of varying lengths: a: 0 [[1,2,3,4,5,6,7,7],[1,2,3,4,5],[5,9,3,2]] 1 [[1,2,3],[6,7],[8,9,10]] and series 'b&apo ...

Converting a string to JSON format with JavaScript

My string is structured in JSON format like this: "{""c1"": ""value1"", ""c2"": ""value2""}" After storing it in an SQLITE database, I use the following Javascript code to retrieve it back as JSON: var req= "SELECT json_column from my_table"; var re ...

Initiating a GET request to retrieve the file generated by the server

I am currently delving into the Mean stack and have encountered a challenge with downloading a file from my server-side application using the Angular front end. Despite successfully generating the file on the back end, clicking the download button on the f ...

The art of swift JavaScript currency conversion based on time

I am in need of transforming a collection of data containing expenses with different dates into an alternative currency. One challenge is that these expenses cover multiple years, so I must consider the changes in exchange rates over time. Does anyone kno ...

Transitioning the existing application from iOS Cordova's UIWebView to WKWebView requires disabling asynchronous JavaScript execution in order to maintain functionality

Previously, in one of our older examples for saving data, we had successfully used the following code in cordova UIWebview without any issues: var filenameID; function getFilenameID() { $.ajax('/jquery/getdata', // request url { success ...

Refresh selected items after inserting data via ajax in CodeIgniter

I have a select list on my view that allows users to add new items using a plus button. However, when a new item is added, the list does not refresh. I don't want to refresh the entire page with an ajax query. Instead, I am trying to implement a metho ...

When transitioning to the production environment, Nuxt.js fails to load images

I am currently working on developing a rather large app. Everything was running smoothly in the development environment without any errors. However, upon switching to the production environment, I started encountering numerous errors. Nuxt seems to be havi ...

Datatables stands out by emphasizing rows across all paginated pages

Encountering an issue with the Datatables plugin when attempting to highlight rows on paginated pages beyond the first one. In the JavaScript code below, you can see where I have commented out adding the class info to all rows. When this is done and you n ...

Creating a new list by grouping elements from an existing list

I have successfully received data from my API in the following format: [ {grade: "Grade A", id: 1, ifsGrade: "A1XX", ifsType: "01XX", points: 22, type: "Type_1"}, {grade: "Grade B", id: 2, ifsGrade: &quo ...

After submitting my form, the Bootstrap Modal does not hide as intended by my Ajax

I am facing an issue with my webpage that displays 6 Bootstrap Cards in 3 columns. Each card contains an image, name, description, and a footer button. When a user clicks on the button, a Bootstrap Modal opens with specific data fetched from a SQL row by I ...

Is there a way to retrieve just the array element as the output instead of the entire object in MongoDB?

Here is the code snippet I am using to display review array data from the restaurant collection object: async get(reviewId) { const restaurantsCollection = await restaurants(); reviewId = ObjectId(reviewId) const r = await restaurantsCollect ...

Issue with Node.js xml2js module: Sitemap attributes are not being recognized during creation

Currently, my project involves utilizing node.js and xml2js to generate an XML sitemap.xml. Everything seems to be in order, but when I try to define attributes like: '$': { 'xmlns': 'http://www.sitemaps.org/schemas/sitemap/0 ...

utilizing jQuery to create dynamic data changes based on JSON file

<div id="rightside"> <h1>John Doe</h1> <p>1980 - 2020 <p><a href="johnswebsite.com">Visit Website</a> <p>Lorem ipsum dolor sit amet, consectetur adi ...

Isolating an array from an object?

I am working with a component that receives props: The data received is logged on the console. https://i.sstatic.net/F3Va4.png What is the best way to extract the array from this object? Before I pass the array to my component, it appears like this: h ...

Encountering difficulties accessing functions from apollo-server-express

I have been following a tutorial and attempting to launch the node server, but I am unable to import these functions from the Apollo package const {graphqlExpress, graphiqlExpress} = require('apollo-server-express'); // importing functions here ...

Struggling to conceal the elusive x button that resets the input field

There is an X box that always appears, which I use to clear the text. However, I would like this X box to only appear when the input has focus and then hide after a word has been entered. Currently, it is visible all the time. https://i.sstatic.net/6Owwi. ...