Generating a distinct datetime string value from an array of nested arrays using JavaScript

I'm facing a challenge where I need to iterate over an array of arrays structure to filter out duplicate datetime string values and then store the unique datetime string values in a new array while ensuring they are sorted. My attempt at using a nested forEach() method failed as it wasn't working as expected.

This is the array of arrays structure:

arr =[
   ["some_value", "2016-11-23 18:11", 1]
   ["some_value", "2016-11-23 18:01", 1]
   ["some_value", "2016-11-23 18:01", 2]
   ["some_value", "2016-11-23 18:01", 1]
   ["some_value", "2016-11-23 18:22", 1]
   ["some_value", "2016-11-23 18:23", 1]
   ["some_value", "2016-11-23 18:25", 1]
   ["some_value", "2016-11-23 18:24", 3]
   ["some_value", "2016-11-23 18:26", 1]
   ["some_value", "2016-11-23 18:27", 1]
];

The desired result:

res = ["2016-11-23 18:01",
       "2016-11-23 18:11", 
       "2016-11-23 18:22",
       "2016-11-23 18:23",
       "2016-11-23 18:24",
       "2016-11-23 18:25",
       "2016-11-23 18:26",
       "2016-11-23 18:27"];

I would appreciate any guidance or tips on how to approach this issue effectively.

Answer №1

To simplify the array of arrays and extract just an array of date strings, you can use the following code:

arr = arrayOfArrays.map(x => x[1])

If you convert this array to a set, you will obtain unique values:

var set = new Set(arr)

If necessary, you can then transform it back into an array:

var uniq = Array.from(set)

For sorting purposes:

uniq.sort((a,b)=> new Date(a) - new Date(b))

var arrayOfArrays = [
   ["some_value", "2016-11-23 18:11", 1],
   ["some_value", "2016-11-23 18:01", 1],
   ["some_value", "2016-11-23 18:01", 2],
   ["some_value", "2016-11-23 18:01", 1],
   ["some_value", "2016-11-23 18:22", 1],
   ["some_value", "2016-11-23 18:23", 1],
   ["some_value", "2016-11-23 18:25", 1],
   ["some_value", "2016-11-23 18:24", 3],
   ["some_value", "2016-11-23 18:26", 1],
   ["some_value", "2016-11-23 18:27", 1],
];

var arr = arrayOfArrays.map(x => x[1])
var set = new Set(arr)

var uniq = Array.from(set)

uniq.sort((a,b)=> new Date(a) - new Date(b))

console.log(uniq)

Answer №2

Using map and Set for Extraction

To extract dates from the array, you can utilize the map function:

const extractedDates = arr.map(data => data[1]);

Subsequently, by storing these dates in a new Set, which retains unique values within an array. By invoking .values on this set, you can retrieve its distinct elements.

arr = [
   ["some_value", "2016-11-23 18:11", 1],
   ["some_value", "2016-11-23 18:01", 1],
   ["some_value", "2016-11-23 18:01", 2],
   ["some_value", "2016-11-23 18:01", 1],
   ["some_value", "2016-11-23 18:22", 1],
   ["some_value", "2016-11-23 18:23", 1],
   ["some_value", "2016-11-23 18:25", 1],
   ["some_value", "2016-11-23 18:24", 3],
   ["some_value", "2016-11-23 18:26", 1],
   ["some_value", "2016-11-23 18:27", 1],
];


const extractedDates = arr.map(item => item[1]);
const uniqueResults = new Set(extractedDates);

console.log('uniqueResults: ', Array.from(uniqueResults))

Expand Your Knowledge!

If you want to delve deeper into sets, take a look at more information here on MDN

An illustration illustrating the concept of functional style using array functions like map/filter/reduce with a hint of humor (assuming onions are excluded during 'filter'):

https://i.sstatic.net/hwkvV.png

Image Source: https://twitter.com/francesc/status/507942534388011008

Answer №3

Utilizing the power of lodash, I find solutions to my coding challenges. The relevance of this tool continues to impress me.

let data =[
    ["value_A", "2016-11-23 18:11", 1],
    ["value_B", "2016-11-23 18:01", 1],
    ["value_C", "2016-11-23 18:01", 2],
    ["value_D", "2016-11-23 18:01", 1],
    ["value_E", "2016-11-23 18:22", 1],
    ["value_F", "2016-11-23 18:23", 1],
    ["value_G", "2016-11-23 18:25", 1],
    ["value_H", "2016-11-23 18:24", 3],
    ["value_I", "2016-11-23 18:26", 1],
    ["value_J", "2016-11-23 18:27", 1]
];

_.map(_.sortBy(_.uniqBy(data, n => n[1]), n => n[1]), n => n[1]);

Answer №4

        const data = data = [
        ["value_1", "2021-10-15 09:30", 1],
        ["value_2", "2021-10-15 10:00", 1],
        ["value_3", "2021-10-15 10:00", 2],
        ["value_4", "2021-10-15 10:00", 1],
        ["value_5", "2021-10-15 10:30", 1],
        ["value_6", "2021-10-15 10:45", 1],
        ["value_7", "2021-10-15 10:50", 1],
        ["value_8", "2021-10-15 10:48", 3],
        ["value_9", "2021-10-15 10:55", 1],
        ["value_10", "2021-10-15 11:00", 1],
     ];
    const datesData = data.map(item => item[1])
    const uniqueDatesArray = datesData.filter(function (element, index) {
        return datesData.indexOf(element) == index;
    });

Answer №5

If you're looking to achieve a specific result, consider implementing the following code:


function onlyUnique(value, index, self) { 
  return self.indexOf(value) === index;
}

var arr =[
  ["some_value", "2016-11-23 18:11", 1],
  ["some_value", "2016-11-23 18:01", 1],
  ["some_value", "2016-11-23 18:01", 2],
  ["some_value", "2016-11-23 18:01", 1],
  ["some_value", "2016-11-23 18:22", 1],
  ["some_value", "2016-11-23 18:23", 1],
  ["some_value", "2016-11-23 18:25", 1],
  ["some_value", "2016-11-23 18:24", 3],
  ["some_value", "2016-11-23 18:26", 1],
  ["some_value", "2016-11-23 18:27", 1]
];

var rest = [];


arr.forEach(function(entry) {

rest.push(entry[1]) 
});

rest.sort();

var finalArr = rest.filter( onlyUnique );

console.log(finalArr);

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

Review a roster of websites every half a minute (Revise pages every half an hour??)

Just starting out with HTML coding! Can someone please provide the code that will allow me to save various webpages and automatically cycle through them every 30 seconds? And also ensure that the webpages are updated every 30 minutes. ...

What is the best way to access the second item using getByRole in React Testing Library when there is no specific name?

I am familiar with using the name option to select the first item here, but how can I go about selecting the second item if it does not have a name identified? -------------------------------------------------- button: Enter "Go": ...

Is the CSS code example provided on the JSXGraph website functioning correctly?

I did my best to replicate this example from the JSXGraph website: Below is the condensed HTML: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Covid Sandbox</title> < ...

Anticipated a response in the form of an object, however, a string was delivered instead

After recently updating to v14 of discordjs, I've been encountering numerous errors, including the one below. It seems a lot has changed since my last coding session, and I'm a bit unsure about what modifications are needed to ensure this ping sl ...

Store the input fields of the chosen table row into an array for iterative processing

I need help with extracting input fields from a specific row in a table and adding them to an array. My goal is to loop through this array later. This is how I currently approach it: let selectedTr = []; let arr = []; $('td input:checked').eac ...

Is it possible to delete an item from both the input button and the list?

Asking for help with an issue -> https://stackblitz.com/edit/dropdown-fill-empty-uecsjw?file=src%2Fapp%2Fapp.component.ts Current problem description. The issue I am facing is that after selecting items from a drop-down menu and then deleting them usi ...

The issue of fonts module resolution in React-Native remains unsolved

I am embarking on a basic build project using 'create-react-native-app' and yarn as the package manager. My main goal is to incorporate 'native-base' for enhancing the user interface. So far, the only addition to my app.js file is a B ...

Modifying the input field value in React

I've been attempting to modify the value of an input field after selecting an item from the SelectField in the MaterialUI library. Despite my efforts, I have not yet succeeded. However, based on my research, everything I have written appears to be cor ...

Update the heading from h2 to h1 tag

Is there a way to modify the product names on all product pages, switching them from h2 to h1? I am seeking a solution to change the product names to h1 using custom code. <h2 itemprop="name" class="product_title likeh2">Aspen Ágykeret Bársony S ...

Changing the title of a webpage dynamically with dropdown menu selections using AngularJS

Seeking assistance with dynamically changing the title of an HTML page based on a selection from a drop-down menu populated by categories retrieved from a remote database using PHP and Ajax in AngularJS. When a category is clicked, I want the page title to ...

Is mastering canvas games a worthwhile pursuit?

Being passionate about creating a canvas game, I have some doubts about whether it's worth the effort. Here's why... With Adobe Flash, you can create highly complex animations, games, and apps. It makes me wonder if there will soon be a program ...

creating an array within a Java for loop

public class Test1 { public static void main () { int N = 10; int M = 100000; for(int i =0; i< N; i++) { int[] box = new int[M]; } } } Does this code result in memory being allocated for an array of ...

Mongoose Exception: Question does not have a constructor

After coming across numerous questions on stack overflow related to this error without finding a solution that works for me, I've decided to ask my own question. (probably due to my limited understanding of javascript/node/mongoose) The modules I am ...

Modify CSS class if the window size is smaller than specified value

Is there a way to modify the attributes of a CSS class if the browser window is less than 600px in height? The current default properties are as follows: .side { height:400px; width:700px; } I am looking to update it to: .side { height:300px; width:550p ...

Creating a Java program to populate a 2D character array from a text file

As a Java beginner, I'm working on populating a 2D character array from an input file. I created a method that accepts a 2D character array as a parameter, reads the file, and saves it as a character array. While I've made progress in setting eve ...

Rearrange elements in groups

I want to reverse an array in chunks of a defined size. Here is a sample of the desired outcome: chunk = 2 arr = [1,2,3,4,5] How can I create an array where the chunks are reversed like this: [2, 1, 4, 3, 5] This is the code I have: arr.each_slice(chu ...

What is the best way to ensure that all of my images are the same size?

I've been working on making my pictures of varying resolutions the same size here, but no matter what I try, it just doesn't seem to work. Here is what I'm getting: . When I change the state to 1, 2, 3, or 4, I want it to look like this: her ...

Enhancing the javascript console output

Take a look at this demonstration: const y = "bar"; console.log(y); => y: bar Is there a way to modify console.log() or use a library like npm package to enhance its functionality? ...

Are you experiencing a strange problem with the CSS button when hovering, clicking, or with the border?

Check out the code for this implementation on jsfiddle: https://jsfiddle.net/xuhang1128/cmkbu07s/2/ I utilized React and React-bootstrap to create it. .design2-statusMonitor { margin-top: 20px; .list-group-item { display: inline-block; ...

Clever method for enabling image uploads upon image selection without needing to click an upload button using JQuery

Is there a way to automatically upload the file without having to click the upload button? Detail : The code below shows an input field for uploading an image, where you have to select the file and then click the "Upload" button to actually upload it: & ...