in the below array i want to filter out records, that match the substring "11/2022" for key StartTime
[
{
StartTime: '17/10/2022 14:45',
Duration: '000:00:44:32',
},
{
StartTime: '17/11/2022 14:45',
Duration: '000:00:44:30',
},
{
StartTime: '18/11/2022 14:45',
Duration: '000:00:44:30',
},
{
StartTime: '17/12/2022 14:45',
Duration: '000:00:44:30',
}
]
expected output:
[
{
StartTime: '17/11/2022 14:45',
Duration: '000:00:44:30',
},
{
StartTime: '18/11/2022 14:45',
Duration: '000:00:44:30',
}
]
CodePudding user response:
you can use the includes function like this
[
{ StartTime: "17/10/2022 14:45", Duration: "000:00:44:32" },
{ StartTime: "17/11/2022 14:45", Duration: "000:00:44:30" },
{ StartTime: "18/11/2022 14:45", Duration: "000:00:44:30" },
{ StartTime: "17/12/2022 14:45", Duration: "000:00:44:30" },
].filter((item) => item.StartTime.includes("11/2022"));
CodePudding user response:
You can use filter() to loop through the array of objects, and for each object item, check whether the StartTime includes() any of the search keyword substring.
const array = [{
StartTime: '17/10/2022 14:45',
Duration: '000:00:44:32',
}, {
StartTime: '17/11/2022 14:45',
Duration: '000:00:44:30',
}, {
StartTime: '18/11/2022 14:45',
Duration: '000:00:44:30',
},
{
StartTime: '17/12/2022 14:45',
Duration: '000:00:44:30',
}
];
const searchKey = '11/2022';
const filteredArray = array.filter(item => item.StartTime.includes(searchKey));
console.log(filteredArray);
Hope it helps!
CodePudding user response:
Just using Array.filter()
can do it
let data = [
{
StartTime: '17/10/2022 14:45',
Duration: '000:00:44:32',
},
{
StartTime: '17/11/2022 14:45',
Duration: '000:00:44:30',
},
{
StartTime: '18/11/2022 14:45',
Duration: '000:00:44:30',
},
{
StartTime: '17/12/2022 14:45',
Duration: '000:00:44:30',
}
]
let result = data.filter(d => d.StartTime.includes('/11/2022'))
console.log(result)
CodePudding user response:
const arr = [
{ StartTime: '17/10/2022 14:45', Duration: '000:00:44:32', },
{ StartTime: '17/11/2022 14:45', Duration: '000:00:44:30', },
{ StartTime: '18/11/2022 14:45', Duration: '000:00:44:30', },
{ StartTime: '17/12/2022 14:45', Duration: '000:00:44:30',}
]
const newArr = arr.filter(elem => elem.StartTime.match("11/2022"))
CodePudding user response:
You can use .filter()
and .includes()
:
const input = [
{ StartTime: '17/10/2022 14:45', Duration: '000:00:44:32', },
{ StartTime: '17/11/2022 14:45', Duration: '000:00:44:30', },
{ StartTime: '18/11/2022 14:45', Duration: '000:00:44:30', },
{ StartTime: '17/12/2022 14:45', Duration: '000:00:44:30', }
];
const result = input.filter(element => {
return element.StartTime.includes("11/2022");
});
console.log(result);