How can I find out the min and the max date from an object?
Currently, I am getting an array like this: min date should be '2010-02-24' and max date should be '2022-10-04'.
Is there any built-in function to do this? Thanks in advance.
{
"2010":[
{
"id":1243,
"eventName":"sample_01",
"categoryType":"CUSTOM_NOTES",
"tags":"tag19",
"startDate":"2010-02-24",
"endDate":"2010-02-26",
"attachments":[
]
}
],
"2022":[
{
"id":1244,
"eventName":"sample_02",
"categoryType":"CUSTOM_NOTES",
"tags":"tag1, tag12, tag3, tag52, tag19",
"startDate":"2022-10-04",
"endDate":"2022-12-12",
"attachments":[
]
},
{
"id":1245,
"eventName":"hello_03",
"categoryType":"CUSTOM_NOTES",
"tags":"tag1, tag12",
"startDate":"2022-06-01",
"endDate":"2010-06-26",
"attachments":[
]
}
]
}
filterEventsByDates = () => {
const filterDateFn = (a, b) => a.startDate.localeCompare(b.startDate);
setDateFiltersToState(filterDateFn);
}
setDateFiltersToState = (filterDateFn) => {
this.setState(state => {
const events = {};
for (const [year, items] of Object.entries(state.events)) {
events[year] = items.slice().filter(filterDateFn);
}
return { events };
});
}
A sort will do the job here, by packing all dates into an array first:
const values = {
"2010":[
{
"id":1243,
"eventName":"sample_01",
"categoryType":"CUSTOM_NOTES",
"tags":"tag19",
"startDate":"2010-02-24",
"endDate":"2010-02-26",
"attachments":[
]
}
],
"2022":[
{
"id":1244,
"eventName":"sample_02",
"categoryType":"CUSTOM_NOTES",
"tags":"tag1, tag12, tag3, tag52, tag19",
"startDate":"2022-10-04",
"endDate":"2022-12-12",
"attachments":[
]
},
{
"id":1245,
"eventName":"hello_03",
"categoryType":"CUSTOM_NOTES",
"tags":"tag1, tag12",
"startDate":"2022-06-01",
"endDate":"2010-06-26",
"attachments":[
]
}
]
};
// include startDate only
const dates = Object.values(values).flatMap(v =>
v.map(({startDate}) => startDate)).sort();
console.log(dates[0], dates.pop());
// include startDate and endDate
const datesAny = Object.values(values).flatMap(v =>
v.flatMap(({startDate, endDate}) => [startDate, endDate])).sort();
console.log(datesAny[0], datesAny.pop());
Here you can make use of reduce function. & check if the date is less or more(with the one stored in accumulator).
const obj = {"2010":[{"id":1243,"eventName":"sample_01","categoryType":"CUSTOM_NOTES","tags":"tag19","startDate":"2010-02-24","endDate":"2010-02-26", "attachments":[ ]} ], "2022":[{ "id":1244, "eventName":"sample_02", "categoryType":"CUSTOM_NOTES", "tags":"tag1, tag12, tag3, tag52, tag19", "startDate":"2022-10-04", "endDate":"2022-12-12", "attachments":[ ] }, { "id":1245, "eventName":"hello_03", "categoryType":"CUSTOM_NOTES", "tags":"tag1, tag12", "startDate":"2022-06-01", "endDate":"2010-06-26", "attachments":[ ] } ] };
const result = Object.values(obj).flat().reduce((a,e)=>{
if(new Date(e.startDate)<new Date(a.min) || !a.min) a.min=e.startDate;
if(new Date(e.startDate)>new Date(a.max)) a.max=e.startDate;
return a;
},{min:null, max:null});
console.log(result);
Related
I am getting an array of object data from service as below:
outputs
array= [
{id:1,Name:GHI,Gender:Male,DOB:12/1/2020},
{id:1,Name:GHI,Gender:Female,DOB:10/1/2020},
{id:2,Name:ABC,Gender:Male,DOB:02/02/2020},
{id:2,Name:ABC,Gender:Female,DOB:03/04/2019},
{id:3,Name:EFG,Gender:Male,DOB:09/09/2010},
{id:3,Name:EFG,Gender:Female,DOB:08/07/2021}
]
I have applied group by function and mapping by using the key
let key="id";
const groupBy=(array,key)=>{
return Object.entries(array.reduce((result,currentvalue)=>{
(result[currentValues[key]]=result[currentValue[key]]||[]).push(
currentvalue
);
return result;
},{})).map(v=>({[key]:v[0],data:v[1]})));
};
I am able to get data like this
[
{
Id:1,
data:
[
{id:1,Name:GHI,Gender:Male,DOB:12/1/2020},
{id:1,Name:GHI,Gender:Female,DOB:10/1/2020}
]
},
{
Id:2,
data:
[
{id:2,Name:ABC,Gender:Male,DOB:02/02/2020},
{id:2,Name:ABC,Gender:Female,DOB:03/04/3019}
]
}...
]
But I need the out put some thing like this I need to group by Id but need the Name of Id something like this
[
{
Name:GHI,
data:[
{id:1,Name:GHI,Gender:Male,DOB:12/1/2020},
{id:1,Name:GHI,Gender:Female,DOB:10/01/2020}
]
},
{
Name:ABC,
data:[
{id:2,Name:ABC,Gender:Male,DOB:02/02/2020},
{id:2,Name:ABC,Gender:Female,DOB:03/04/2019}
]
},
{
Name:EFG,
data:[
{id:3,Name:EFG,Gender:Male,DOB:09/09/2010},
{id:3,Name:EFG,Gender:Male,DOB:08/07/2021}
]
}
]
Please let me know how to retrieve data in expected format to display on UI.
try with the below code.
var arr = [
{id:1,Name:"GHI",Gender:"Male",DOB:"12/1/2020"},
{id:1,Name:"GHI",Gender:"Female",DOB:"10/1/2020"},
{id:2,Name:"ABC",Gender:"Male",DOB:"02/02/2020"},
{id:2,Name:"ABC",Gender:"Female",DOB:"03/04/2019"},
{id:3,Name:"EFG",Gender:"Male",DOB:"09/09/2010"},
{id:3,Name:"EFG",Gender:"Female",DOB:"08/07/2021"}
]
let temp = {}
arr.forEach((obj) => {
temp[obj.Name] = temp[obj.Name] || [];
temp[obj.Name].push(obj);
});
let output = Object.entries(temp).map(obj => {
return {"Name": obj[0], "data": obj[1]}
});
console.log(JSON.stringify(output, null, 2));
You may go simpler and more readable:
let result = {};
for (const data of array) {
const { Name } = data;
if (!result[Name]) {
result[Name] = { Name, data: [data] };
} else {
result[Name].data.push(data);
}
}
I have the following function, where its extracting some data from some files and return in an array
const extractTestCases = () => {
const filesArray = []
const filterTestSuite = files.filter(test => test.includes('.test.ts'))
filterTestSuite.forEach(testsuite => {
const feature = regexMatcher(testsuite, featureRegex, 1)
const testSuites = fs.readFileSync(testsuite, { encoding: "utf8" });
const testCases = regexMatcher(testSuites, TestRegex, 1)
filesArray.push({ [feature]: testCases })
})
return filesArray;
}
which gives me an output like the following
[
{
featureCustom: [ 'somethig' ]
},
{
featureInsp: [
'bla bla',
'foo foo'
]
}
]
how to make it generate an output like the following
[
{
"features": [
{
"featureCustom": [ 'somethig'
]
},
{
"featureInsp": ['bla bla','foo foo'
]
}
]
}
]
Something like?...
const extractTestCases = () => {
const filesArray = []
filesArray.push({ [feature]: testCases })
return [
{
features: filesArray
}
];
}
I have an array object as follows,
const data = [
{
"order_id":"ORDCUTHIUJ",
"branch_code":"MVPA",
"total_amt":199500,
"product_details":[
{
"image":"CC252.jpg",
"cate":"Mobile Accessories"
}
]
},
{
"order_id":"ORHOGFD79L",
"branch_code":"PBVR",
"total_amt":325880,
"product_details":[
{
"image":"1617382086515.jpg",
"cate":"Mobile Accessories"
},
{
"image":"1617382322759.jpg",
"cate":"Mobile Accessories"
},
{
"image":"CC251.jpg",
"cate":"Mobile Accessories"
}
]
},
{
"order_id":"ORIYDJLYSJ",
"branch_code":"MVPA",
"total_amt":1549500,
"product_details":[
{
"image":"CC250.jpg",
"cate":"Mobile Accessories"
},
{
"image":"CC256.jpg",
"cate":"Mobile Accessories"
}
]
}
]
what I want to achieve is to build a new array based on this, but I want to group the data with the same branch code under one object.
Expected Output:
const newData =
[
{
MVPA: [
{
order_id: 'ORIYDJLYSJ',
(otherdetails)
},
{
order_id: 'ORDCUTHIUJ',
(otherdetails
}
]
},
PBVR: [
{
order_id: 'ORHOGFD79L',
(otherdetails)
}
]
can someone help me out on how to achieve this.? I want a general solution, bcoz this data could be longer than this when I get from DB.
You can do it with Array.reduce.
data.reduce((o, a) => (o[a.branch_code] = [ ...(o[a.branch_code] || []), a], o), {})
First create an object which collects data with branch_code.
const obj = data.reduce((map,obj)=>{
if(obj.branch_code in map){
map[obj.branch_code].push({...obj})
}
else{
map[obj.branch_code]=[{...obj}]
}
return map
},{})
This gives
{MVPA: Array(2), PBVR: Array(1)}
Then,map over the keys of the above object to create your required array.
const result = Object.keys(obj).map(key => ({[key]:
[...obj[key]]}))
console.log('result',result)
This gives
(2) [{…}, {…}]
0: {MVPA: Array(2)}
1: {PBVR: Array(1)}
const uniqueBranchCode = [...new Set(data.map(i => i.branch_code))] // Get unique branch_code
const newData = uniqueBranchCode
.map(order => data.filter(orderSpecific => orderSpecific.branch_code === order)) // Filter to group together by branch_code
.map(item => ({[item[0].branch_code]: item})) // Assign key and return elements
const data = [
{
"order_id":"ORDCUTHIUJ",
"branch_code":"MVPA",
"total_amt":199500,
"product_details":[
{
"image":"CC252.jpg",
"cate":"Mobile Accessories"
}
]
},
{
"order_id":"ORHOGFD79L",
"branch_code":"PBVR",
"total_amt":325880,
"product_details":[
{
"image":"1617382086515.jpg",
"cate":"Mobile Accessories"
},
{
"image":"1617382322759.jpg",
"cate":"Mobile Accessories"
},
{
"image":"CC251.jpg",
"cate":"Mobile Accessories"
}
]
},
{
"order_id":"ORIYDJLYSJ",
"branch_code":"MVPA",
"total_amt":1549500,
"product_details":[
{
"image":"CC250.jpg",
"cate":"Mobile Accessories"
},
{
"image":"CC256.jpg",
"cate":"Mobile Accessories"
}
]
}
]
const uniqueBranchCode = [...new Set(data.map(i => i.branch_code))]
const newData = uniqueBranchCode
.map(order => data.filter(orderSpecific => orderSpecific.branch_code === order))
.map(item => ({[item[0].branch_code]: item}))
console.log(newData)
You can try this way
const data =[{"order_id":"ORDCUTHIUJ","branch_code":"MVPA","total_amt":199500,"product_details":[{"image":"CC252.jpg","cate":"Mobile Accessories"}]},{"order_id":"ORHOGFD79L","branch_code":"PBVR","total_amt":325880,"product_details":[{"image":"1617382086515.jpg","cate":"Mobile Accessories"},{"image":"1617382322759.jpg","cate":"Mobile Accessories"},{"image":"CC251.jpg","cate":"Mobile Accessories"}]},{"order_id":"ORIYDJLYSJ","branch_code":"MVPA","total_amt":1549500,"product_details":[{"image":"CC250.jpg","cate":"Mobile Accessories"},{"image":"CC256.jpg","cate":"Mobile Accessories"}]}];
const result = data.reduce((acc, {order_id, branch_code, product_details}) => {
acc[branch_code] ??= {[branch_code]: []};
acc[branch_code][branch_code].push({order_id, product_details});
return acc;
}, {});
console.log(Object.values(result));
let obj = {}
function comp(x) {
const f1 = data.filter(function (i) {
return i.branch_code === x
})
return f1
}
for (let i = 0; i < data.length; i++) {
obj[`${data[i].branch_code}`] = comp(data[i].branch_code)
}
console.log(obj)
I have following datas,
let response =[
{
"14714733": [
"Android Testing-1",
"Test special manual",
"Test Manual",
"SECESC"
]
},
{
"10110133": [
"Android Testing-1",
"SECESC"
]
}
]
let shipment =[
{
"masterDocumentNumber": "14714733"
},
{
"masterDocumentNumber": "10110133",
}
]
And
let flagIns=[
{
"fieldValue": "SECESC",
"fieldDescription": "Security Escort"
},
{
"fieldValue": "INS",
"fieldDescription": "Inspection"
}
]
How to iterate and add Corresponding response data in to shipment data as follows,
Desired output
let shipment =[
{
"masterDocumentNumber": "14714733",
"instructions":[
{"index":0,"instruction":"Android Testing-1"},
{"index":1,"instruction":"Test special manual"},
{"index":2,"instruction":"Test Manual"},
{"index":3,"instruction":"Security Escort"}
]
},
{
"masterDocumentNumber": "10110133",
"instructions":[
{"index":0,"instruction":"Android Testing-1"},
{"index":1,"instruction":"Security Escort"}
]
}
]
Note that if flagIns has same data in response then it need to be replaced with it's description.
You should be able to use a function similar to this.. it appears you just need to match up keys and values from the different objects..
function aggregate(response, shipment, flagIns) {
return shipment.map(({ masterDocumentNumber }) => {
let output = { masterDocumentNumber, instructions: [] }
let res = response.find(r => masterDocumentNumber in r);
if (res) {
res[masterDocumentNumber].forEach((r, i) => {
let ins = flagIns.find(fi => fi.fieldValue === r);
output.instructions.push({
index: i,
instruction: ins ? ins.fieldDescription : r
})
})
}
return output;
});
}
const response = [
{
"14714733": [
"Android Testing-1",
"Test special manual",
"Test Manual",
"SECESC"
]
},
{
"10110133": ["Android Testing-1", "SECESC"]
}
];
const shipment = [
{
masterDocumentNumber: "14714733"
},
{
masterDocumentNumber: "10110133"
}
];
const flagIns = [
{
fieldValue: "SECESC",
fieldDescription: "Security Escort"
},
{
fieldValue: "INS",
fieldDescription: "Inspection"
}
];
console.log(aggregate(response, shipment, flagIns));
let shipment =[];
//create array
response.map((res)=>{
//get keys
let key=Object.keys(res)
//loop in instructions
let instructions=[];
res[key].map((val,i)=>{
let inst ={
"index":i,
"instruction":val
}
instructions.push(inst)
})
let m={
"masterDocumentNumber":key,
"instructions":instructions
}
shipment.push(m)
})
console.log(JSON.stringify(shipment))
First flatten the response and flagIns array of objects and then iterate over the shipment array to get the desired output.
let response =[
{
"14714733": [
"Android Testing-1",
"Test special manual",
"Test Manual",
"SECESC"
]
},
{
"10110133": [
"Android Testing-1",
"SECESC"
]
}
]
let shipment =[
{
"masterDocumentNumber": "14714733"
},
{
"masterDocumentNumber": "10110133",
}
]
let flagIns=[
{
"fieldValue": "SECESC",
"fieldDescription": "Security Escort"
},
{
"fieldValue": "INS",
"fieldDescription": "Inspection"
}
]
const responseRes = response.reduce(function (acc, item) {
return Object.assign(acc, item);
}, {});
// responseRes
// {
// '10110133': [ 'Android Testing-1', 'SECESC' ],
// '14714733': [
// 'Android Testing-1',
// 'Test special manual',
// 'Test Manual',
// 'SECESC'
// ]
// }
const flagInsRes = flagIns.reduce(function (acc, item) {
return Object.assign(acc, {
[item.fieldValue]: item.fieldDescription});
}, {});
// flagInsRes
// { SECESC: 'Security Escort', INS: 'Inspection' }
const shipmentRes = shipment.map(obj => {
const temp = {};
temp.masterDocumentNumber = obj.masterDocumentNumber
temp.instructions = responseRes[obj.masterDocumentNumber]
.map((item, index) => {
return {
"index":index,
"instruction":flagInsRes[item] ? flagInsRes[item] : item}
});
return temp;
});
console.log(shipmentRes);
{
"rResponse":{
"rDetailsList":[
{
"rDate":"April 01, 2018",
"rList":[
{
"aName":"GOKQG C HQFUDHFPX",
"aNumber":"P3799838628"
},
{
"aName":"IGNDPJR D EKYJYC",
"aNumber":"P3899820579"
}
]
},
{
"rDate":"Jan 01, 2018",
"rList":[
{
"aName":"",
"aNumber":"A39A4035073"
},
{
"aName":"YVTLW K SIGLC",
"aNumber":"A270M040558"
}
]
}
]
}
}
getFilteredResult(rDetails, searchText) {
const regex = new RegExp(searchText, 'i');
let result= rDetails.filter(a =>
a.rList.some(rItem=>
(rItem.aName.search(regex) > -1) ||
(rItem.aNumber.search(regex) > -1)
))
console.log(result,"filteredResults")
return result;
}
let result=getFilteredResult(rResponse.rDetailsList, "A270M040558"):
I am using the above function for filtering the data based on search string.
I want to filter the nested array of object keep the structure of the object same
The output of the above function is below, where i am getting all object of a list instead of getting only one object which matches the search text
{
"rResponse": {
"rDetailsList": [{
"rDate": "Jan 01, 2018",
"rList": [{
"aName": "",
"aNumber": "A39A4035073"
},
{
"aName": "YVTLW K SIGLC",
"aNumber": "A270M040558"
}
]
}]
}
}
The expected Output is
{
"rResponse": {
"rDetailsList": [{
"rDate": "Jan 01, 2018",
"rList": [
{
"aName": "YVTLW K SIGLC",
"aNumber": "A270M040558"
}
]
}]
}
}
You have 2 arrays, so you need to filter the first one then the second one :
const rDetailsList = [
{
"rDate":"April 01, 2018",
"rList":[
{
"aName":"GOKQG C HQFUDHFPX",
"aNumber":"P3799838628"
},
{
"aName":"IGNDPJR D EKYJYC",
"aNumber":"P3899820579"
}
]
},
{
"rDate":"Jan 01, 2018",
"rList":[
{
"aName":"",
"aNumber":"A39A4035073"
},
{
"aName":"YVTLW K SIGLC",
"aNumber":"A270M040558"
}
]
}
];
const myFilter = (arr, num) => {
const rDetails = arr.filter(det => !!det.rList.find(l => l.aNumber === num));
return rDetails.map(det => {
det.rList = det.rList.filter(l => l.aNumber === num);
return det;
});
};
console.log(myFilter(rDetailsList, 'A270M040558'));
const res = _.chain(rDetailsList)
.map(rDetail => _.assign( // iterate array and set filtered rList
{}, // use new object to avoid mutations
rDetail,
{ rList: _.filter(rDetail.rList, { aNumber: 'A270M040558' }) }
))
.reject(rDetail => _.isEmpty(rDetail.rList)) // remove elements with empty rList
.value();