Merge 2 arrays without overwrite in Nodejs [duplicate] - javascript

This question already has answers here:
Merge two arrays containing objects and remove duplicate values
(7 answers)
Closed 2 days ago.
I want to merge two arrays from the db into one without overwriting the data, I have tried different options with lodash merge, concatenate and other but without luck. Can you please help!
My objects:
places: [
{ placeId: 2, place: 'a' },
{ placeId: 3, place: 'b' },
{ placeId: 4, place: 'c' },
{ placeId: 5, place: 'd' },
{ placeId: 6, place: 'e' }
]
places: [
{ placeId: 12, place: 'f' },
{ placeId: 13, place: 'g' },
{ placeId: 14, place: 'h' },
{ placeId: 21, place: 'i' },
{ placeId: 22, place: 'j' },
{ placeId: 29, place: 'k' },
{ placeId: 30, place: 'l' }
]
i want to get this
places:[
{ placeId: 2, place: 'a' },
{ placeId: 3, place: 'b' },
{ placeId: 4, place: 'c' },
{ placeId: 5, place: 'd' },
{ placeId: 6, place: 'e' },
{ placeId: 12, place: 'f' },
{ placeId: 13, place: 'g' },
{ placeId: 14, place: 'h' },
{ placeId: 21, place: 'i' },
{ placeId: 22, place: 'j' },
{ placeId: 29, place: 'k' },
{ placeId: 30, place: 'l' }
]

you can do like this:
const allPlaces = places1.concat(places2)
or
const allPlaces = [...places1,...places2]

Related

Javascript nested array and filter

Here is my code
https://codepen.io/hobbesa/pen/jOGREKy?editors=1111
I am trying to get price of only weekdays.How do I do that?
this.getPriceWeekDay = this.StrategypricingDetail.map((rec) =>
rec.map((daysOfWeek) => {
return daysOfWeek;
}),
You can first, filter items which doesn't contain Saturday or Sunday by using filter and find methods, and then iterate over filtered list by map method to extract just price property, like this:
let StrategypricingDetail = [ { id: 3, name: "test", price: 30, daysOfWeek: [ { id: 1, name: "Monday" }, { id: 2, name: "Tuesday" }, { id: 3, name: "Wednesday" } ] }, { id: 23, name: "Testing2", price: 10, daysOfWeek: [ { id: 1, name: "Monday" }, { id: 2, name: "Tuesday" } ] }, { id: 13, name: "Testing3", price: 14, daysOfWeek: [ { id: 1, name: "Saturaday" }, { id: 2, name: "Sunday" } ] } ];
const weekDaysPrice = StrategypricingDetail.filter(({daysOfWeek}) => !daysOfWeek.find(({name}) => name == 'Saturaday' || name == 'Sunday')).map(({price}) => price);
console.log(weekDaysPrice);
One solution you could use below.
let strategypricingDetail = [
{
id: 3,
name: "test",
price: 30,
daysOfWeek: [
{ id: 1, name: "Monday" },
{ id: 2, name: "Tuesday" },
{ id: 3, name: "Wednesday" }
]
},
{
id: 23,
name: "Testing2",
price: 10,
daysOfWeek: [
{ id: 1, name: "Monday" },
{ id: 2, name: "Tuesday" }
]
},
{
id: 13,
name: "Testing3",
price: 14,
daysOfWeek: [
{ id: 1, name: "Saturaday" },
{ id: 2, name: "Sunday" }
]
}
];
let finalList = [];
// Create list of eligible days for the search
let daysToInclude = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday"
];
strategypricingDetail.forEach((item, index) => {
for (let i = 0; i < item.daysOfWeek.length; i++) {
// Check if the day is in the eligible list
if (daysToInclude.includes(item.daysOfWeek[i].name)) {
finalList.push(item);
break;
// When found, break out of the search after adding it to the final list.
}
}
});
console.log(finalList)
In this solution, you loop through the available items, and then compare each item's 'daysOfWeel' list with a list of eligible days.
As soon as it finds one, it'll stop searching, and add that item to a new list, until you end with the list of appropriate days.
//StrategypricingDetail is the whole json
const StrategypricingDetail = [
{
id: 3,
name: "test",
price: 30,
daysOfWeek: [
{ id: 1, name: "Monday" },
{ id: 2, name: "Tuesday" },
{ id: 3, name: "Wednesday" }
]
},
{
id: 23,
name: "Testing2",
price: 10,
daysOfWeek: [
{ id: 1, name: "Monday" },
{ id: 2, name: "Tuesday" }
]
},
{
id: 13,
name: "Testing3",
price: 14,
daysOfWeek: [
{ id: 1, name: "Saturaday" },
{ id: 2, name: "Sunday" }
]
}
];
const weekends = ["Saturaday","Sunday"]
// Approach
// we have to filter some element based on condition
// condition will be days should not belong to weekends
this.getPriceWeekDay = StrategypricingDetail.filter((rec) => {
for(let dayIndex = 0 ; dayIndex < rec.daysOfWeek.length; dayIndex++){
const dayName = rec.daysOfWeek[dayIndex].name;
if(weekends.includes(dayName)){
return;
}
}
return rec;
}).map(({price}) => price);
console.log(getPriceWeekDay);

find method not returning '0th' matched object react, or react-native or javascript

Not getting all matched objects, its is returning all objects except '{ ID:0, Name: 'General Group' }', i want all matched objects
let arrDashboardIconGroups = [
{ ID:0, Name: 'General Group' },
{ ID: 1, Name: 'Patient Administration' },
{ ID: 2, Name: 'Medical Charts' },
{ ID: 3, Name: 'Medical Procedures' },
{ ID: 13, Name: 'Purchase' },
{ ID: 14, Name: 'Sales' },
{ ID: 5, Name: 'Insurance' },
{ ID: 4, Name: 'Cash' },
{ ID: 6, Name: 'Pharmacy' },
{ ID: 7, Name: 'Inventory' },
{ ID: 8, Name: 'Lab' },
{ ID: 9, Name: 'Imaging' },
{ ID: 10, Name: 'In Patient' },
{ ID: 11, Name: 'System Administration' },
{ ID: 12, Name: 'Accounting' }
]
const getMatchedobjects=()=> {
let result = [0,1,2,3,4,]
let matchedArray = arrDashboardIconGroups.filter(val =>result.find(
(items)=>items == val.ID))
console.log(matchedArray)
}
getMatchedobjects()
You are returning the value of
result.find((items) => items == val.ID)
In the first case, the value returned is 0 which is a falsy value. So It won't include in the final filter result.
You can run the below code and see the returning values.
let arrDashboardIconGroups = [
{ ID: 0, Name: "General Group" },
{ ID: 1, Name: "Patient Administration" },
{ ID: 2, Name: "Medical Charts" },
{ ID: 3, Name: "Medical Procedures" },
{ ID: 13, Name: "Purchase" },
{ ID: 14, Name: "Sales" },
{ ID: 5, Name: "Insurance" },
{ ID: 4, Name: "Cash" },
{ ID: 6, Name: "Pharmacy" },
{ ID: 7, Name: "Inventory" },
{ ID: 8, Name: "Lab" },
{ ID: 9, Name: "Imaging" },
{ ID: 10, Name: "In Patient" },
{ ID: 11, Name: "System Administration" },
{ ID: 12, Name: "Accounting" },
];
const getMatchedobjects = () => {
let result = [0, 1, 2, 3, 4];
let matchedArray = arrDashboardIconGroups.filter((val) => {
const returnResult = result.find((items) => items == val.ID);
console.log(returnResult);
return returnResult;
// result.includes(val.ID)
});
console.log(matchedArray);
};
getMatchedobjects();
Alternatively, you can use includes
let arrDashboardIconGroups = [
{ ID: 0, Name: "General Group" },
{ ID: 1, Name: "Patient Administration" },
{ ID: 2, Name: "Medical Charts" },
{ ID: 3, Name: "Medical Procedures" },
{ ID: 13, Name: "Purchase" },
{ ID: 14, Name: "Sales" },
{ ID: 5, Name: "Insurance" },
{ ID: 4, Name: "Cash" },
{ ID: 6, Name: "Pharmacy" },
{ ID: 7, Name: "Inventory" },
{ ID: 8, Name: "Lab" },
{ ID: 9, Name: "Imaging" },
{ ID: 10, Name: "In Patient" },
{ ID: 11, Name: "System Administration" },
{ ID: 12, Name: "Accounting" },
];
const getMatchedobjects = () => {
let result = [0, 1, 2, 3, 4];
let matchedArray = arrDashboardIconGroups.filter((val) => result.includes(val.ID));
console.log(matchedArray);
};
getMatchedobjects();
Issue
Find returns a value/object (the first matching), but it seems you want to filter the arrDashboardIconGroups array by those that match an id specified in the result array. When result[0] is returned, 0 is the value, which is falsey, and the filter doesn't return the element from the arrDashboardIconGroups array.
Solution
Use Array.prototype.some to return the boolean that filter needs to include an element in the result array.
let arrDashboardIconGroups = [
{ ID:0, Name: 'General Group' },
{ ID: 1, Name: 'Patient Administration' },
{ ID: 2, Name: 'Medical Charts' },
{ ID: 3, Name: 'Medical Procedures' },
{ ID: 13, Name: 'Purchase' },
{ ID: 14, Name: 'Sales' },
{ ID: 5, Name: 'Insurance' },
{ ID: 4, Name: 'Cash' },
{ ID: 6, Name: 'Pharmacy' },
{ ID: 7, Name: 'Inventory' },
{ ID: 8, Name: 'Lab' },
{ ID: 9, Name: 'Imaging' },
{ ID: 10, Name: 'In Patient' },
{ ID: 11, Name: 'System Administration' },
{ ID: 12, Name: 'Accounting' }
];
const getMatchedobjects = () => {
let result = [0,1,2,3,4,];
let matchedArray = arrDashboardIconGroups.filter(val => result.some((items)=>items == val.ID));
console.log(matchedArray);
}
getMatchedobjects();
Alternatively you could also check that result array includes the matching id.
let arrDashboardIconGroups = [
{ ID:0, Name: 'General Group' },
{ ID: 1, Name: 'Patient Administration' },
{ ID: 2, Name: 'Medical Charts' },
{ ID: 3, Name: 'Medical Procedures' },
{ ID: 13, Name: 'Purchase' },
{ ID: 14, Name: 'Sales' },
{ ID: 5, Name: 'Insurance' },
{ ID: 4, Name: 'Cash' },
{ ID: 6, Name: 'Pharmacy' },
{ ID: 7, Name: 'Inventory' },
{ ID: 8, Name: 'Lab' },
{ ID: 9, Name: 'Imaging' },
{ ID: 10, Name: 'In Patient' },
{ ID: 11, Name: 'System Administration' },
{ ID: 12, Name: 'Accounting' }
];
const getMatchedobjects=()=> {
let result = [0,1,2,3,4,];
let matchedArray = arrDashboardIconGroups.filter(val => result.includes(val.ID)) ;
console.log(matchedArray);
}
getMatchedobjects();
find() returns value of the first element in the provided array that satisfies the provided testing function. Since 0 is a falsy value, it does not include it in the final array. See MDN Docs
You can map the result array, and use arrDashboardIconGroups's find function, and return the matching objects.
let arrDashboardIconGroups = [
{ ID: 0, Name: 'General Group' },
{ ID: 1, Name: 'Patient Administration' },
{ ID: 2, Name: 'Medical Charts' },
{ ID: 3, Name: 'Medical Procedures' },
{ ID: 13, Name: 'Purchase' },
{ ID: 14, Name: 'Sales' },
{ ID: 5, Name: 'Insurance' },
{ ID: 4, Name: 'Cash' },
{ ID: 6, Name: 'Pharmacy' },
{ ID: 7, Name: 'Inventory' },
{ ID: 8, Name: 'Lab' },
{ ID: 9, Name: 'Imaging' },
{ ID: 10, Name: 'In Patient' },
{ ID: 11, Name: 'System Administration' },
{ ID: 12, Name: 'Accounting' }
]
const getMatchedobjects=()=> {
let result = [0, 1,2,3,4,99] //99 for trial
let matchedArray = result.map((res)=>arrDashboardIconGroups.find((val)=>val.ID == res)).filter(Boolean);
console.log(matchedArray)
}
getMatchedobjects()

Calculate percentile rank using javascript for each user in array of json objects based on user's overall place

Using javascript, how can I calculate the percentile rank for each participant in a results list where person with place = 1 (Joe) has a 100% rank since they won a race, for instance, but then all other people's ranks are lower from there? Here are some sample results. Can someone please help?
const results = [{
name: 'joe',
place: 1,
rank: '100%'
}, {
name: 'roger',
place: 2,
rank: '?'
}, {
name: 'heather',
place: 3,
rank: '?'
}, {
name: 'craig',
place: 4,
rank: '?'
}, {
name: 'sally',
place: 5,
rank: '?'
}, {
name: 'cory',
place: 6,
rank: '?'
}, {
name: 'joel',
place: 7,
rank: '?'
}];
You can subtract one less than each person's rank from the number of people and divide by the number of people to get the percentage rank.
const results = [{
name: 'joe',
place: 1,
rank: '?'
}, {
name: 'roger',
place: 2,
rank: '?'
}, {
name: 'heather',
place: 3,
rank: '?'
}, {
name: 'craig',
place: 4,
rank: '?'
}, {
name: 'sally',
place: 5,
rank: '?'
}, {
name: 'cory',
place: 6,
rank: '?'
}, {
name: 'joel',
place: 7,
rank: '?'
}];
results
.forEach(person=>person.rank
= (+((results.length - person.place + 1) / results.length * 100).toFixed(2)) + '%');
console.log(results);

GroupBy with Multiple Columns using Lodash or Underscore in Javascript

Getting Problem while converting JSON structure. My JSON Structure is as below.
const member = [{
memberId: 4,
memberName: 'ABC',
age: 22,
eventId: 5,
eventName: 'Dance'
},
{
memberId: 4,
memberName: 'ABC',
age: 22,
eventId: 6,
eventName: 'Music'
},
{
memberId: 4,
memberName: 'ABC',
age: 22,
eventId: 7,
eventName: 'FootBall'
},
{
memberId: 5,
memberName: 'PQR',
age: 24,
eventId: 6,
eventName: 'Music'
},
{
memberId: 5,
memberName: 'PQR',
age: 24,
eventId: 5,
eventName: 'Dance'
},
]
Here I have two members with associated events. And I want to convert JSON as follows.
const member = [
{
memberId: 4,
memberName: 'ABC',
age: 22,
events: [
{
id: 5,
name: 'Dance'
},
{
id: 6,
name: 'Music'
},
{
id: 7,
name: 'FootBall'
}
]
},
{
memberId: 5,
memberName: 'PQR',
age: 24,
events: [
{
id: 6,
name: 'Music'
},
{
id: 5,
name: 'Dance'
}
]
}
]
I tried creating the structure using below code but it doesn't provide as the desired output. It just creates two Key-Value pair.
var result = _.chain(member)
.groupBy("memberId")
.pairs()
.map(function(currentItem) {
return _.object(_.zip(["memberId", "events"], currentItem));
})
.value();
I don't know how to add other values of JSON in the hierarchy.
After you group the items, map them. Take the 1st item of each group, and remove the event properties, and spread it. To get the the events data, map the group's items and take only the relevant event properties:
const member = [{"memberId":4,"memberName":"ABC","age":22,"eventId":5,"eventName":"Dance"},{"memberId":4,"memberName":"ABC","age":22,"eventId":6,"eventName":"Music"},{"memberId":4,"memberName":"ABC","age":22,"eventId":7,"eventName":"FootBall"},{"memberId":5,"memberName":"PQR","age":24,"eventId":6,"eventName":"Music"},{"memberId":5,"memberName":"PQR","age":24,"eventId":5,"eventName":"Dance"}]
const result = _(member)
.groupBy('memberId')
.map(group => ({
..._.omit(_.head(group), ['eventId', 'eventName']),
events: _.map(group, o => ({ id: o.eventId, name: o.eventName }))
}))
.value();
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
And the same solution using underscore:
const member = [{"memberId":4,"memberName":"ABC","age":22,"eventId":5,"eventName":"Dance"},{"memberId":4,"memberName":"ABC","age":22,"eventId":6,"eventName":"Music"},{"memberId":4,"memberName":"ABC","age":22,"eventId":7,"eventName":"FootBall"},{"memberId":5,"memberName":"PQR","age":24,"eventId":6,"eventName":"Music"},{"memberId":5,"memberName":"PQR","age":24,"eventId":5,"eventName":"Dance"}]
const result = _.chain(member) // <- change for underscore
.groupBy('memberId')
.map(group => ({
..._.omit(_.head(group), ['eventId', 'eventName']),
events: _.map(group, o => ({ id: o.eventId, name: o.eventName }))
}))
.value();
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"></script>

How would I compare the two to properly sort in order?

Objective is to distinguish the two arrays, and console log the products array in order by its price range, I tried using a nested for-loop to see if this can work out but hasn't gone off in the right track, was also thinking about using lo dash as well. How would I be able to compare the id's between the two and push them in order by price?
/*
Your task is to write a function or set of functions that console logs out the products ordered by price
*/
var products = [
{ id: 1, name: 'Buzzy' },
{ id: 2, name: 'Bytrex' },
{ id: 3, name: 'CactiDance' },
{ id: 4, name: 'CactiLoops' },
{ id: 5, name: 'Cadaver Jelly' },
{ id: 6, name: 'Caffeine Serene' },
{ id: 7, name: 'Cajun Sation' },
{ id: 8, name: 'Call it Green' },
{ id: 9, name: 'Callflex' },
{ id: 10, name: 'Calling Card Shark' },
{ id: 11, name: 'Calque' },
{ id: 12, name: 'Camel Meal Tea' },
{ id: 13, name: 'Camelot Chamomile' },
{ id: 14, name: 'Campxotica' },
{ id: 15, name: 'Camus the Killer Tale' },
{ id: 16, name: 'Candecor' },
{ id: 17, name: 'Candelarium' },
{ id: 18, name: 'CandID' },
{ id: 19, name: 'Candlelight Vittles' },
{ id: 20, name: 'Candy Ask' },
{ id: 21, name: 'Candy Floss' },
];
var prices = [
{ id: 6, price: 55 },
{ id: 14, price: 22 },
{ id: 15, price: 57 },
{ id: 4, price: 41 },
{ id: 18, price: 9 },
{ id: 17, price: 3 },
{ id: 2, price: 73 },
{ id: 7, price: 43 },
{ id: 5, price: 78 },
{ id: 1, price: 91 },
{ id: 8, price: 58 },
{ id: 16, price: 69 },
{ id: 13, price: 74 },
{ id: 19, price: 14 },
{ id: 21, price: 25 },
{ id: 12, price: 84 },
{ id: 20, price: 8 },
{ id: 9, price: 94 },
{ id: 10, price: 36 },
{ id: 3, price: 34 },
{ id: 11, price: 71 },
];
You can use map & findIndex. map will return a new array. Inside the callback function of map use findIndex and use it to find the index of the object where the id matches.
var products = [{
id: 1,
name: 'Buzzy'
},
{
id: 2,
name: 'Bytrex'
},
{
id: 3,
name: 'CactiDance'
},
{
id: 4,
name: 'CactiLoops'
},
{
id: 5,
name: 'Cadaver Jelly'
},
{
id: 6,
name: 'Caffeine Serene'
},
{
id: 7,
name: 'Cajun Sation'
},
{
id: 8,
name: 'Call it Green'
},
{
id: 9,
name: 'Callflex'
},
{
id: 10,
name: 'Calling Card Shark'
},
{
id: 11,
name: 'Calque'
},
{
id: 12,
name: 'Camel Meal Tea'
},
{
id: 13,
name: 'Camelot Chamomile'
},
{
id: 14,
name: 'Campxotica'
},
{
id: 15,
name: 'Camus the Killer Tale'
},
{
id: 16,
name: 'Candecor'
},
{
id: 17,
name: 'Candelarium'
},
{
id: 18,
name: 'CandID'
},
{
id: 19,
name: 'Candlelight Vittles'
},
{
id: 20,
name: 'Candy Ask'
},
{
id: 21,
name: 'Candy Floss'
},
];
var prices = [{
id: 6,
price: 55
},
{
id: 14,
price: 22
},
{
id: 15,
price: 57
},
{
id: 4,
price: 41
},
{
id: 18,
price: 9
},
{
id: 17,
price: 3
},
{
id: 2,
price: 73
},
{
id: 7,
price: 43
},
{
id: 5,
price: 78
},
{
id: 1,
price: 91
},
{
id: 8,
price: 58
},
{
id: 16,
price: 69
},
{
id: 13,
price: 74
},
{
id: 19,
price: 14
},
{
id: 21,
price: 25
},
{
id: 12,
price: 84
},
{
id: 20,
price: 8
},
{
id: 9,
price: 94
},
{
id: 10,
price: 36
},
{
id: 3,
price: 34
},
{
id: 11,
price: 71
},
];
let newArr = prices.map(function(item) {
let k = products.findIndex(elem => elem.id === item.id);
if (k !== -1) {
return products[k]
}
});
console.log(newArr)
You could sort the prices array first. Then loop through it and get the products for each id using find like this:
var products = [{id:1,name:"Buzzy"},{id:2,name:"Bytrex"},{id:3,name:"CactiDance"},{id:4,name:"CactiLoops"},{id:5,name:"Cadaver Jelly"},{id:6,name:"Caffeine Serene"},{id:7,name:"Cajun Sation"},{id:8,name:"Call it Green"},{id:9,name:"Callflex"},{id:10,name:"Calling Card Shark"},{id:11,name:"Calque"},{id:12,name:"Camel Meal Tea"},{id:13,name:"Camelot Chamomile"},{id:14,name:"Campxotica"},{id:15,name:"Camus the Killer Tale"},{id:16,name:"Candecor"},{id:17,name:"Candelarium"},{id:18,name:"CandID"},{id:19,name:"Candlelight Vittles"},{id:20,name:"Candy Ask"},{id:21,name:"Candy Floss"}],
prices = [{id:6,price:55},{id:14,price:22},{id:15,price:57},{id:4,price:41},{id:18,price:9},{id:17,price:3},{id:2,price:73},{id:7,price:43},{id:5,price:78},{id:1,price:91},{id:8,price:58},{id:16,price:69},{id:13,price:74},{id:19,price:14},{id:21,price:25},{id:12,price:84},{id:20,price:8},{id:9,price:94},{id:10,price:36},{id:3,price:34},{id:11,price:71}];
prices.sort((a, b) => a.price - b.price)
.forEach(p => {
console.log(products.find(a => a.id === p.id))
})

Categories

Resources