Hey I am working on a attendance project in reactjs , I am facing a problem that I received an array of attendances e.g (in range of last two weeks ) . All I need is filter an array of distinct date, not the time but only date . (Time can be different in one date)
let dates = [
{id: 51, attendanceTime: '2022-12-26T06:07:02.000Z'}
,
{id: 52, attendanceTime: '2022-11-26T06:07:36.000Z' }
,
{id: 53, attendanceTime: '2022-10-12T06:28:43.000Z'}
,
{id: 54, attendanceTime: '2023-01-01T06:48:53.000Z'}
,
{id: 55, attendanceTime: '2022-12-26T06:56:23.000Z'}
];
I have tried methods but gettime() compare all not only date , getDate() compare only Day not month and year , So I need to filter such that it only differentiate on only date (day,month,year) and filter my array of distinct array. I need result like
const result=[
{id: 51, attendanceTime: '2022-12-26T06:07:02.000Z'}
,
{id: 52, attendanceTime: '2022-11-26T06:07:36.000Z' }
,
{id: 53, attendanceTime: '2022-10-12T06:28:43.000Z'}
,
{id: 54, attendanceTime: '2023-01-01T06:48:53.000Z'}
]
this is required result of distinct date array
CodePudding user response:
You can try something like that:
let dates = [
{id: 51, attendanceTime: '2022-12-26T06:07:02.000Z'},
{id: 52, attendanceTime: '2022-11-26T06:07:36.000Z' },
{id: 53, attendanceTime: '2022-10-12T06:28:43.000Z'},
{id: 54, attendanceTime: '2023-01-01T06:48:53.000Z'},
{id: 55, attendanceTime: '2022-12-26T06:56:23.000Z'}
];
let distinct = [];
for(let i = 0; i < dates.length; i ){
let dateFromDates = dates[i].attendanceTime.split("T");
let duplicate = distinct.filter(dateFromDistinct => dateFromDistinct == dateFromDates[0]);
if(duplicate.length == 0){
distinct.push(dateFromDates[0]);
}
}
console.log(distinct);
- Time complexity: O(n^2)
- Space complexity: O(n)
Also date format must be in that format that you share.
CodePudding user response:
You can use Array.filter() and Array.substring() to find unique values
let dates = [
{id: 51, attendanceTime: '2022-12-26T06:07:02.000Z'},
{id: 52, attendanceTime: '2022-11-26T06:07:36.000Z' },
{id: 53, attendanceTime: '2022-10-12T06:28:43.000Z'},
{id: 54, attendanceTime: '2023-01-01T06:48:53.000Z'},
{id: 55, attendanceTime: '2022-12-26T06:56:23.000Z'}
];
let uniqueDate=dates.filter((value,ind,arr)=>arr.findIndex(value2=>(value2.attendanceTime.substring(0, 10)===value.attendanceTime.substring(0, 10)))===ind)
console.log('Original',dates, '\nUnique',uniqueDate)
Working
filter() method creates new array with elements that pass test provided by a function.
syntax: dates.filter(function(currentValue, index, arr), thisValue)
substring() method extracts characters between two indices, from a string, and returns the substring.
Syntax: string.substring(start, end)