Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How to find max salary in each department?
let emp =[
{
'name':"A",
'sal':86879,
'dept':1
},
{
'name':"B",
'sal':3453674,
'dept':2
},
{
'name':"C",
'sal':568867,
'dept':3
},
{
'name':"D",
'sal':34661,
'dept':1
},
{
'name':"E",
'sal':896556,
'dept':2
},
{
'name':"F",
'sal':67678,
'dept':3
},
{
'name':"G",
'sal':45654,
'dept':4
},{
'name':"H",
'sal':35677,
'dept':4
}
];
You can look through each entry in the array, and check for the highest in each department by storing them in a separate object like this
const maxSal = {};
emp.forEach(e=>{
if (!maxSal[e.dept] || maxSal[e.dept] < e.sal){
maxSal[e.dept] = e.sal;
}
});
maxSal is an object with the keys of the department, the value is the highest salary
You could reduce the array by taking dept and val and collect the max values in an object.
const
data = [{ name: "A", sal: 86879, dept: 1 }, { name: "B", sal: 3453674, dept: 2 }, { name: "C", sal: 568867, dept: 3 }, { name: "D", sal: 34661, dept: 1 }, { name: "E", sal: 896556, dept: 2 }, { name: "F", sal: 67678, dept: 3 }, { name: "G", sal: 45654, dept: 4 }, { name: "H", sal: 35677, dept: 4 }],
result = data.reduce(
(r, { dept, sal }) => (r[dept] = Math.max(r[dept] ?? -Number.MAX_VALUE, sal), r ),
{}
);
console.log(result);
here you go findHighestSallary function will return the highest salary just pass the department no. as an argument.
let emp =[
{
'name':"A",
'sal':86879,
'dept':1
},
{
'name':"B",
'sal':3453674,
'dept':2
},
{
'name':"C",
'sal':568867,
'dept':3
},
{
'name':"D",
'sal':34661,
'dept':1
},
{
'name':"E",
'sal':896556,
'dept':2
},
{
'name':"F",
'sal':67678,
'dept':3
},
{
'name':"G",
'sal':45654,
'dept':4
},{
'name':"H",
'sal':35677,
'dept':4
}
];
function findHighestSallary(dept) {
let myarray = [];
emp.map((x) => {
if(x.dept === dept){
myarray.push(x);
}
})
myarray.sort(function(a, b) {
return b.sal - a.sal;
});
return myarray[0].sal;
}
console.log(findHighestSallary(1));
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to create expectedObj from currentObj to be sent as response to the API. How can I do it?
The "value" and "label" will always have same values.
These are fixed set of keys. ignore_whitespace is not needed in expectedObj. No other keys are required to be removed.
let currentObj = {
"partnerId": "1",
"platform": {
"label": "ADP",
"value": "ADP"
},
"subPlatform": {
"value": "Health",
"label": "Health"
},
"activeIndicator": {
"value": "Inactive",
"label": "Inactive"
},
"partnerNotes": "",
"ignore_whitespace": false
}
let expectedObj={
"partnerId": "1",
"platform": "ADP",
"subPlatform": Health,
"activeIndicator": "Inactive",
"partnerNotes": ""
}
What I have tried is this
for let (item in currentObj) {
something
}
This will do the transforms you need (as discussed in the comments, no more keys are expected, values are always the same as labels, etc):
let currentObj = {
"partnerId": "1",
"platform": {
"label": "ADP",
"value": "ADP"
},
"subPlatform": {
"value": "Health",
"label": "Health"
},
"activeIndicator": {
"value": "Inactive",
"label": "Inactive"
},
"partnerNotes": "",
"ignore_whitespace": false
}
let expected = {
...currentObj,
platform: currentObj.platform.value,
subPlatform: currentObj.subPlatform.value,
activeIndicator: currentObj.activeIndicator.value,
}
delete expected.ignore_whitespace;
console.log(expected);
Something like this should do what you're looking for:
const expectedObj = Object.entries(currentObj).reduce((a, [k, v]) => {
if (v?.value !== undefined) a[k] = v.value;
else a[k] = v;
return a;
}, {});
Expand this code snippet for a working example:
const currentObj = {
partnerId: '1',
platform: {
label: 'ADP',
value: 'ADP',
},
subPlatform: {
value: 'Health',
label: 'Health',
},
activeIndicator: {
value: 'Inactive',
label: 'Inactive',
},
partnerNotes: '',
ignore_whitespace: false,
};
const expectedObj = Object.entries(currentObj).reduce((a, [k, v]) => {
if (v?.value !== undefined) a[k] = v.value;
else a[k] = v;
return a;
}, {});
console.log(expectedObj);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I currently want to extract in this array:
[
{
"date":"2021-04-21",
"time":"05:12",
"status":"Collected",
"caption":"Parcel collected"
},
{
"date":"2019-08-21",
"time":"12:04",
"status":"Awaiting Collection",
"caption":"Parcel is awaiting collection"
},
{
"date":"2019-08-21",
"time":"12:03",
"status":"In-transit",
"caption":"Parcel is in-transit"
}
]
to transform to this array whereas i check on the date and time for the new nested array like this:
[
{
"date":"2021-04-21",
"time":"05:12",
"status":"Collected",
"caption":"Parcel collected"
},
{
"date":"2019-08-21",
[
{
"time":"12:04",
"status":"Awaiting Collection",
"caption":"Parcel is awaiting collection"
},
{
"time":"12:03",
"status":"In-transit",
"caption":"Parcel is in-transit"
}
]
}
]
I have tried filter and reduce but will be much same as initialized array as it takes the whole [i] as unique and not date as unique.
As in your snippet, you need to store nested data in some kind of container. I've named it data.
const array = [
{
date: "2021-04-21",
time: "05:12",
status: "Collected",
caption: "Parcel collected",
},
{
date: "2019-08-21",
time: "12:04",
status: "Awaiting Collection",
caption: "Parcel is awaiting collection",
},
{
date: "2019-08-21",
time: "12:03",
status: "In-transit",
caption: "Parcel is in-transit",
},
];
const result = array.reduce((acc, curr) => {
const index = acc.findIndex((o) => o.date === curr.date);
if (index !== -1) {
const { date, ...rest } = acc[index];
const existTime = curr.time;
const existStatus = curr.status;
const existCaption = curr.caption;
if (!rest.data) {
acc[index] = {
date: date,
data: [
{ ...rest },
{ time: existTime, status: existStatus, caption: existCaption },
],
};
} else {
acc[index].data.push({
time: existTime,
status: existStatus,
caption: existCaption,
});
}
} else {
acc.push({ ...curr });
}
return acc;
}, []);
console.log(result);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I would like to convert my below object to a specific format
Product: { "alias":"d8156ad9-06af-45ca-a8eb-17f6148f1bd2",
"manufacturing_company":{
"alias":"1",
"name":"Company",
"status":1
},
"form":{
"alias":"2",
"name":"Suppository",
"status":1
},
"generic":{
"alias":"1",
"name":"Esomeprazole",
"status":1
},
"name":"AA",
"trading_price":15,
"purchase_price":10,
"pack_size":"10",
"is_salesable":true,
"primary_unit":{
"alias":"1",
"name":"Form1",
"status":2
},
"secondary_unit":{
"alias":"1",
"name":"Form1",
"status":2
},
"conversion_factor":25,
"code":"201",
"species":"drfgfgd",
"strength":"96",
"full_name":"AA 96",
"status":1,
"category":{
"alias":"8",
"name":"Test2",
"status":1
},
"subgroup":{
"alias":"4",
"name":"CDCD",
"status":1,
"product_group":{
"id":9,
"alias":"1",
"name":"zsdfasd",
"status":1
}
}
}
to
Product: { "alias":"d8156ad9-06af-45ca-a8eb-17f6148f1bd2",
"manufacturing_company":"1",
"form":"2",
"generic":"1",
"name":"AA",
"trading_price":15,
"purchase_price":10,
"pack_size":"10",
"is_salesable":true,
"primary_unit":"1",
"secondary_unit":"1",
"conversion_factor":25,
"code":"201",
"species":"drfgfgd",
"strength":"96",
"full_name":"AA 96",
"status":1,
"category":"8",
"subgroup":"4"
}
Loop through the object and create a new one based on whether the values are scalar or not:
let obj={Product:{alias:"d8156ad9-06af-45ca-a8eb-17f6148f1bd2",manufacturing_company:{alias:"1",name:"Company",status:1},form:{alias:"2",name:"Suppository",status:1},generic:{alias:"1",name:"Esomeprazole",status:1},name:"AA",trading_price:15,purchase_price:10,pack_size:"10",is_salesable:!0,primary_unit:{alias:"1",name:"Form1",status:2},secondary_unit:{alias:"1",name:"Form1",status:2},conversion_factor:25,code:"201",species:"drfgfgd",strength:"96",full_name:"AA 96",status:1,category:{alias:"8",name:"Test2",status:1},subgroup:{alias:"4",name:"CDCD",status:1,product_group:{id:9,alias:"1",name:"zsdfasd",status:1}}}};
let resObj = {}
Object.entries(obj.Product).map(([key, value]) => {
if(typeof value === "object"){
resObj[key] = value.alias
}else{
resObj[key] = value
}
})
console.log(resObj)
You could take for object alias or the value for creating a new object.
var data = { alias: "d8156ad9-06af-45ca-a8eb-17f6148f1bd2", manufacturing_company: { alias: "1", name: "Company", status: 1 }, form: { alias: "2", name: "Suppository", status: 1 }, generic: { alias: "1", name: "Esomeprazole", status: 1 }, name: "AA", trading_price: 15, purchase_price: 10, pack_size: "10", is_salesable: true, primary_unit: { alias: "1", name: "Form1", status: 2 }, secondary_unit: { alias: "1", name: "Form1", status: 2 }, conversion_factor: 25, code: "201", species: "drfgfgd", strength: "96", full_name: "AA 96", status: 1, category: { alias: "8", name: "Test2", status: 1 }, subgroup: { alias: "4", name: "CDCD", status: 1, product_group: { id: 9, alias: "1", name: "zsdfasd", status: 1 } } },
result = Object.fromEntries(Object
.entries(data)
.map(([k, v]) => [k, v && typeof v === 'object'
? v.alias
: v]
)
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If data is the json you want to convert , then use the below code to get the desired result.
Object.keys(data).reduce((result , current)=>{
var value = "";
if(typeof(data[current]) == "object")
{
value = data[current]["alias"]
}
else{
value = data[current]
}
var d = {}
d[current] = value;
Object.assign(result,d);
return result;
},{})
This question already has answers here:
Get object keys with the highest value in Javascript
(4 answers)
Closed 3 years ago.
var food = {
"fruit":{"brand":{"grgrdgdr":true,"ggyugy":true}, "sold":2},
"vegetable" :{"brand":{"htrhtr":true},"sold": 1},
"snack":{"brand":{"htrhr":true},"sold": 3},
"other":{"brand":{"gdhshd":true},"sold":1},
....
...
...
};
How do I console log the object name that sold the most,
in this case should be the word snack.
I find this link, but its structure is not similar to mine.
Get object keys with the highest value in Javascript
any help is appreciated
thanks in advance
You could sort by the values property and get the first item.
var food = { fruit: { brand: { grgrdgdr: true, ggyugy: true }, sold: 2 }, vegetable: { brand: { htrhtr: true }, sold: 1 }, snack: { brand: { htrhr: true }, sold: 3 }, other: { brand: { gdhshd: true }, sold: 1 } };
result = Object
.keys(food)
.sort((a, b) => food[b].sold - food[a].sold)
[0];
console.log(result);
Find the max value first, and then filter the object to get objects having max sold value
var food = {
"fruit":{"brand":{"grgrdgdr":true,"ggyugy":true}, "sold":2},
"vegetable" :{"brand":{"htrhtr":true},"sold": 1},
"snack":{"brand":{"htrhr":true},"sold": 3},
"other":{"brand":{"gdhshd":true},"sold":1}}
var maxSold = Math.max(...Object.values(food).map(o=> o.sold))
var result = Object.keys(food).filter(o => food[o].sold ===maxSold)
console.log(result) //this will given all objects with max sold value
You can use a variable & iterate the array twice. In the first iteration get the highest sold. Then on second iteration add the products whose sold value is same as the highest sold
var food = {
"fruit": {
"brand": {
"grgrdgdr": true,
"ggyugy": true
},
"sold": 5
},
"vegetable": {
"brand": {
"htrhtr": true
},
"sold": 1
},
"snack": {
"brand": {
"htrhr": true
},
"sold": 3
},
"other": {
"brand": {
"gdhshd": true
},
"sold": 1
},
"someOtherfruit": {
"brand": {
"grgrdgdr": true,
"ggyugy": true
},
"sold": 5
}
}
let highestSold = 0;
let newObj = [];
for (let keys in food) {
if (food[keys].sold > highestSold) {
highestSold = food[keys].sold
}
}
for (let keys in food) {
if (food[keys].sold === highestSold) {
newObj.push(food[keys])
}
}
console.log(newObj[0])
var food = {
"fruit":{"brand":{"grgrdgdr":true,"ggyugy":true}, "sold":2},
"vegetable" :{"brand":{"htrhtr":true},"sold": 1},
"snack":{"brand":{"htrhr":true},"sold": 3},
"other":{"brand":{"gdhshd":true},"sold":1},
};
function getMostExpensivesKey(array) {
let key = Object.keys(array)[0];
Object.keys(array).forEach(function(k) {
if(array[k].sold > array[key].sold) {
key = k;
}
});
return key;
}
console.log(getMostExpensivesKey(food));
Your posted link Get object keys with the highest value in Javascript
was quite close
var food = {
"fruit":{"brand":{"grgrdgdr":true,"ggyugy":true}, "sold":2},
"vegetable" :{"brand":{"htrhtr":true},"sold": 1},
"snack":{"brand":{"htrhr":true},"sold": 3},
"other":{"brand":{"gdhshd":true},"sold":1}
},
result = Object
.keys(food)
.sort(function(a, b) {
return food[b].sold - food[a].sold;
})[0] // or .slice(0, 1);
console.log(result,food[result]);
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
This question already has answers here:
How to get distinct values from an array of objects in JavaScript?
(63 answers)
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 6 years ago.
I have array with obejcts email and Id so I want delete duplicate elements who have similar ID's.
Example:
var newarray=[
{
Email:"test1#gmail.com",
ID:"A"
},
{
Email:"test2#gmail.com",
ID:"B"
},
{
Email:"test3#gmail.com",
ID:"A"
},
{
Email:"test4#gmail.com",
ID:"C"
},
{
Email:"test4#gmail.com",
ID:"C"
}
];
Now I need to delete Duplicate elements which have ID's are common.In the sence I am expecting final Array is
var FinalArray=[
{
Email:"test1#gmail.com",
ID:"A"
},
{
Email:"test2#gmail.com",
ID:"B"
},
{
Email:"test5#gmail.com",
ID:"C"
}
];
Use Array.prototype.filter to filter out the elements and to keep a check of duplicates use a temp array
var newarray = [{
Email: "test1#gmail.com",
ID: "A"
}, {
Email: "test2#gmail.com",
ID: "B"
}, {
Email: "test3#gmail.com",
ID: "A"
}, {
Email: "test4#gmail.com",
ID: "C"
}, {
Email: "test5#gmail.com",
ID: "C"
}];
// Array to keep track of duplicates
var dups = [];
var arr = newarray.filter(function(el) {
// If it is not a duplicate, return true
if (dups.indexOf(el.ID) == -1) {
dups.push(el.ID);
return true;
}
return false;
});
console.log(arr);
You could filter it with a hash table.
var newarray = [{ Email: "test1#gmail.com", ID: "A" }, { Email: "test2#gmail.com", ID: "B" }, { Email: "test3#gmail.com", ID: "A" }, { Email: "test4#gmail.com", ID: "C" }, { Email: "test5#gmail.com", ID: "C" }],
filtered = newarray.filter(function (a) {
if (!this[a.ID]) {
this[a.ID] = true;
return true;
}
}, Object.create(null));
console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }
ES6 with Set
var newarray = [{ Email: "test1#gmail.com", ID: "A" }, { Email: "test2#gmail.com", ID: "B" }, { Email: "test3#gmail.com", ID: "A" }, { Email: "test4#gmail.com", ID: "C" }, { Email: "test5#gmail.com", ID: "C" }],
filtered = newarray.filter((s => a => !s.has(a.ID) && s.add(a.ID))(new Set));
console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you can use Javascript libraries such as underscore or lodash, I recommend having a look at _.uniq function in their libraries. From lodash:
_.uniq(array, [isSorted=false], [callback=_.identity], [thisArg])
Here you have to use like below,
var non_duplidated_data = _.uniq(newarray, 'ID');
Another solution using Array.prototype.reduce and a hash table - see demo below:
var newarray=[ { Email:"test1#gmail.com", ID:"A" }, { Email:"test2#gmail.com", ID:"B" }, { Email:"test3#gmail.com", ID:"A" }, { Email:"test4#gmail.com", ID:"C" }, { Email:"test5#gmail.com", ID:"C" } ];
var result = newarray.reduce(function(hash){
return function(prev,curr){
!hash[curr.ID] && (hash[curr.ID]=prev.push(curr));
return prev;
};
}(Object.create(null)),[]);
console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}