I am writing code in ReactJs
I have an Array of object like this
[
{
createdBy: "DEF",
createdDate: "2020",
lastModifiedDate: "2021",
name: "John Doe",
section: {
createdBy: "A2C",
status: "ACTIVE",
},
sectionName: "Mechanical",
},
{
createdBy: "ABC",
createdDate: "2020",
lastModifiedDate: "2021",
name: "John Doe",
section: {
createdBy: "ABC",
status: "ACTIVE",
},
sectionName: "Mechanical",
},
{
createdBy: "ABC",
createdDate: "2020",
lastModifiedDate: "2021",
name: "John Doe",
section: {
createdBy: "XYZ",
status: "ACTIVE",
},
sectionName: "Mechanical",
},
{
createdBy: "A1C",
createdDate: "2020",
lastModifiedDate: "2021",
name: "John Wick",
section: {
createdBy: "ABC",
status: "ACTIVE",
},
sectionName: "Mechanical",
},
];
here, the only thing same is the "name", so on the basis of name, I want the duplicate objects to be stored in the new array.
I have tried it like this
let temp = [];
for (const i of response) {
if (!temp.includes(i)) {
temp.push(i);
console.log("if loop", i);
} else {
console.log("else loop", response);
}
}
but the control never goes to else as it considers each object as different.
I need the first occurrence of an object as it is, but when the "name" element gets repeated, that object should get stored in a new array.
Expected:-
[
{
createdBy: "ABC",
createdDate: "2020",
lastModifiedDate: "2021",
name: "John Doe",
section: {
createdBy: "ABC",
status: "ACTIVE",
},
sectionName: "Mechanical",
},
{
createdBy: "ABC",
createdDate: "2020",
lastModifiedDate: "2021",
name: "John Doe",
section: {
createdBy: "XYZ",
status: "ACTIVE",
},
sectionName: "Mechanical",
},
]
You can maintain a tracker object for checking if an object with the same name has already been visited or not. If visited then push the object into a duplicate array otherwise push into unique array. Try this-
const data=[{createdBy:"ABC",createdDate:"2020",lastModifiedDate:"2021",name:"John Doe",section:{createdBy:"ABC",status:"ACTIVE"},sectionName:"Mechanical"},{createdBy:"ABC",createdDate:"2020",lastModifiedDate:"2021",name:"John Doe",section:{createdBy:"A2C",status:"ACTIVE"},sectionName:"Mechanical"},{createdBy:"A1C",createdDate:"2020",lastModifiedDate:"2021",name:"John Doe",section:{createdBy:"ABC",status:"ACTIVE"},sectionName:"Mechanical"}];
const track = {};
const unique = [];
const duplicate = [];
for (const item of data) {
if (track?.[item.name] === undefined) {
unique.push(item);
track[item.name] = true;
} else {
duplicate.push(item);
}
}
console.log('unique', unique);
console.log('duplicate', duplicate);
.as-console-wrapper {min-height: 100%!important; top: 0}
let count=0
let temp = response;
let duplicateArray=[]
for (const i of response) {
count=0
if(temp.find(t => t.name === i.name)){
count++
}
if(count>0){
duplicateArray.push(i)
}
}
Not sure if this will solve the particular issue you have but
not use helprjs
const arr1 = [{ id: 1, name: 'Jack'}, { id: 2, name: 'Jack'}];
const arr2 = [{ id: 2, name: 'Jane'}, { id: 3, name: 'Rod'}];
mergeArrays(arr1, arr2, "name");
// [{ id: 1, name: 'Jack'}, { id: 2, name: 'Jane'}, { id: 3, name: 'Rod'}];
mergeArrays(arr1, arr2, "id");
// [{ id: 1, name: 'Jack'}, { id: 2, name: 'Jack'}, { id: 3, name: 'Rod'}];
Check out the demo
Related
I am having trouble filtering an object array, based on a given property.
The object array looks something like this:
someData: [{
id: "123",
personData: [
{
personName: "John Smith",
personId: "125443",
categoryId: "B1",
description: "description"
}}]}];
I want to group the personData based on the categoryId, but represent the category grouping by its categoryName (instead of Id as this will not make much sense to the user).
There are a series of categories which are contained in a json in the following format:
const groups = {
data: [
{
categoryName: "Banking",
categoryId: "B1",
description: "Financial sector"
},
{
categoryName: "Retail",
categoryId: "R1",
description: "Retail and customer experience"
}
]
};
How would I go about filtering based on these conditions? All help is much appreciated! I am using react and typescript
Once filtered the data should look like this:
Banking
personName: John Smith
personId: 125443
Retail
personName: Judie Smith
personId: 124938
You can try groupBy on that person data.
const products = [
{ name: 'apples', category: 'fruits' },
{ name: 'oranges', category: 'fruits' },
{ name: 'potatoes', category: 'vegetables' }
];
const groupByCategory = products.groupBy(product => {
return product.category;
});
console.log(groupByCategory);
// {
// 'fruits': [
// { name: 'apples', category: 'fruits' },
// { name: 'oranges', category: 'fruits' },
// ],
// 'vegetables': [
// { name: 'potatoes', category: 'vegetables' }
// ]
// }
I think something along the lines of this function would return what you need.
const data = [
{
categoryName: "Banking",
categoryId: "B1",
description: "Financial sector"
},
{
categoryName: "Retail",
categoryId: "R1",
description: "Retail and customer experience"
}
];
function groupByProperty(arrayOfObjects, property) {
return arrayOfObjects.reduce((acc, curr) => {
const key = curr[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(curr);
return acc;
}, {});
}
const dataByCategoryName = groupByProperty(data, "categoryName");
console.log(dataByCategoryName);
/* Output
{
Banking: [{
categoryId: "B1",
categoryName: "Banking",
description: "Financial sector"
}],
Retail: [{
categoryId: "R1",
categoryName: "Retail",
description: "Retail and customer experience"
}]
}
*/
I have a list of data like below:
The data consist of 6 categories (bags, shoes, girls, bags, and boys) and all of them store the same data (id, items(array: desc, id, imageUrl, name, price), routeName, title).
Now, I want to loop through all categories and just retrieve their name from the 'items', how can I do this?
I have tried the code below and I just can retrieve the name from one of the categories. Are there any ways to get all of the names from all collections? Thanks for helping me.
const { bags, shoes, girls, bags, boys } = collections;
const {items} = bags;
console.log(items.map(item => item.name));
I used this sample data object which mapping with your example. using below array functions can get the result more efficiently.
const data = {
bags: {
id: 1,
items: [
{ desc: "abc", id: 1, imageUrl: "url", name: "Rabbit Crossbody", price:"$10" },
{ desc: "qwe", id: 2, imageUrl: "url", name: "Cat Crossbody", price:"$10" },
{ desc: "pqr", id: 3, imageUrl: "url", name: "Parrot Crossbody", price:"$10" },
],
routeName:"bags",
title:"Bags"
},
boys: {
id: 1,
items: [
{ desc: "abc", id: 1, imageUrl: "url", name: "Lion Crossbody", price:"$10" },
{ desc: "qwe", id: 2, imageUrl: "url", name: "Dog Crossbody", price:"$10" },
{ desc: "pqr", id: 3, imageUrl: "url", name: "Crow Crossbody", price:"$10" },
],
routeName:"boys",
title:"Boys"
},
girls: {
id: 1,
items: [
{ desc: "abc", id: 1, imageUrl: "url", name: "Pig Crossbody", price:"$10" },
{ desc: "qwe", id: 2, imageUrl: "url", name: "Hen Crossbody", price:"$10" },
{ desc: "pqr", id: 3, imageUrl: "url", name: "fish Crossbody", price:"$10" },
],
routeName:"girls",
title:"Girls"
}};
const categories = Object.keys(data); // extract categories
const filteredNames = categories.map(category => {
const items = data[category].items; // extract items of each category
return items.map(item => item.name); // extract names of items into new[]
});
console.log('names', filteredNames.flat());
// ["Rabbit Crossbody", "Cat Crossbody", "Parrot Crossbody", "Lion Crossbody", "Dog Crossbody", "Crow Crossbody", "Pig Crossbody", "Hen Crossbody", "fish Crossbody"]
Try 2 loops:
const allNames = [];
for (const collection of Object.values(collections)) {
for(const item of collection.items) {
allNames.push(item.name);
}
}
console.log(allNames);
It's possible to do this with array functions too, but a loop is often the most obvious.
let project = {
title: "some title",
participants: [{
_id: "12345678",
name: "John"
}, {
_id: "44332211",
name: "Jackson"
}, {
_id: "55667788",
name: "Steve"
}]
}
let users = [{
_id: "12345678",
name: "John"
}, {
_id: "44332211",
name: "Jackson"
}, {
_id: "09876543",
name: "Aaron"
}, {
_id: "55667788",
name: "Steve"
}, {
_id: "22334455",
name: "Xavier"
}]
How do I list out all the users that are NOT part of the project participants? includes does not work because project is an object...
array.filter + array.some will work:
let project = {
title: "some title",
participants: [{
_id: "12345678",
name: "John"
}, {
_id: "44332211",
name: "Jackson"
}, {
_id: "55667788",
name: "Steve"
}]
}
let users = [{
_id: "12345678",
name: "John"
}, {
_id: "44332211",
name: "Jackson"
}, {
_id: "09876543",
name: "Aaron"
}, {
_id: "55667788",
name: "Steve"
}, {
_id: "22334455",
name: "Xavier"
}]
let result = users.filter(user => !project.participants.some(p => p._id === user._id));
console.log(result);
You can also make use of find with filter:
var users = [{ _id: "12345678", name: "John"}, { _id: "44332211", name: "Jackson"}, { _id: "09876543", name: "Aaron"}, { _id: "55667788", name: "Steve"}, { _id: "22334455", name: "Xavier"}];
var project = { title: "some title", participants: [{ _id: "12345678", name: "John" }, { _id: "44332211", name: "Jackson" }, { _id: "55667788", name: "Steve" }]};
var result = users.filter(k=>!project.participants.find(p=>p._id==k._id));
console.log(result);
Using Array.map and Array.filter
let project = { title: "some title",
participants: [{_id: "12345678", name: "John"},
{_id: "44332211", name: "Jackson"},
{_id: "55667788", name: "Steve"}]
}
let users = [{ _id: "12345678", name: "John"},
{ _id: "44332211", name: "Jackson"},
{ _id: "09876543", name: "Aaron"},
{ _id: "55667788", name: "Steve"},
{ _id: "22334455", name: "Xavier"}];
var participants = project.participants.map(function(p){ return p._id; })
var non_participants = users.filter(function(user){
return participants.indexOf(user._id) == -1;
});
console.log(non_participants);
I would first extract the participant ids into a Set for fast lookup. Then filter the users and check if the id is not included in the set (using has).
let project = {
title: "some title",
participants: [
{ _id: "12345678", name: "John" },
{ _id: "44332211", name: "Jackson" },
{ _id: "55667788", name: "Steve" },
]
};
let users = [
{ _id: "12345678", name: "John" },
{ _id: "44332211", name: "Jackson" },
{ _id: "09876543", name: "Aaron" },
{ _id: "55667788", name: "Steve" },
{ _id: "22334455", name: "Xavier" },
];
const participantIds = new Set(project.participants.map(participant => participant._id));
const usersWithoutProject = users.filter(user => !participantIds.has(user._id));
console.log(usersWithoutProject);
There are two object array, some of them have the same key, I'd like to merge the same key in the first array. I have pasted my code.I used nested loop, but the performance was bad O(n²). Maybe I need another method to enhance performance.(I can't use ES6 for some reason, so I'll appreciate if it is the ES5 method.)
var people = [
{
id: "001",
name: "David",
age: 29
},
{
id: "002",
name: "Lucia",
age: 41
},
{
id: "003",
name: "Steve",
age: 18
}
];
var address = [
{
id: "001",
city: "Barcelona"
},
{
id: "002",
city: "Paris"
},
{
},
{
id: "003",
city: "Tokyo"
},
{
id: "004",
city: "Barcelona"
}
];
My code
people.forEach(function(item) {
var id = item.id;
address.forEach(function(location) {
if (location.id == id) {
item.address = location.address
}
});
});
Result
var people = [
{
id: "001",
name: "David",
age: 29,
city: "Barcelona"
},
{
id: "002",
name: "Lucia",
age: 41,
city: "Paris"
},
{
id: "003",
name: "Steve",
age: 18,
city: "Tokyo"
}
];
The new people array is I preferred.
You could take a Map with all addresses and then map new object with extended properties of the map.
This approach takes all properties of address objects.
var people = [{ id: "001", name: "David", age: 29 }, { id: "002", name: "Lucia", age: 41 }, { id: "003", name: "Steve", age: 18 }],
address = [{ id: "001", city: "Barcelona" }, { id: "002", city: "Paris" }, {}, { id: "003", city: "Tokyo" }, { id: "004", city: "Barcelona" }],
map = new Map(address.map(o => [o.id, o])),
result = people.map(o => Object.assign({}, o, map.get(o.id)));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Make a Map with cities by id, and use it when iterating over the people array to find out the city:
let cities = new Map(address.map(a => [a.id, a.city]));
let people2 = people.map(p => ( {...p, city: cities.get(p.id)} ));
You could use Array#map to iterate over people, and Array#find to find the corresponding address from id within iterations:
const people = [{id: "001",name: "David",age: 29 },{ id: "002", name: "Lucia", age: 41
},{ id: "003", name: "Steve", age: 18 }],
address = [{ id: "001", city: "Barcelona" },{ id: "002", city: "Paris" },{ },{ id: "003", city: "Tokyo" },{ id: "004", city: "Barcelona" }];
console.log(
people.map(p => ({
...p,
...address.find(a => (p.id === a.id))
}))
);
However, that's supposing that the properties' name of address's items are not the same as people's ones.
The code below is not tested but it should work
// create an object to store them
const mergedItems = {};
// merge the 2 arrays so you only map them once (just for shorter code)
people.concat(address).map(entity => {
// add each entity on the object and id as a key
mergedItems[entity.id] = {
// if the key exist, it will merge it with the new entity
...mergedItems[entity.id],
...entity,
}
)
// this is your merged items
// Object.values will convert it from object to array
const finalItems = Object.values(mergedItems);
I used map instead of for loop because it is faster: https://codeburst.io/javascript-map-vs-foreach-f38111822c0f
I have used Object.assign method to add values from address
var people = [{ id: "001", name: "David", age: 29 }, { id: "002", name: "Lucia", age: 41 }, { id: "003", name: "Steve", age: 18 }],
address = [{ id: "001", city: "Barcelona" }, { id: "002", city: "Paris" }, {}, { id: "003", city: "Tokyo" }, { id: "004", city: "Barcelona" }];
people.forEach(function(item,pos){
Object.assign(item,{},address[address.findIndex(o=>o.id == item.id)]);
});
console.log(people);
I have array of objects as follows:
[
{
company: "CompanyName",
id: "1",
userProfile: {
id: "2",
telephone: "",
user: {
email: "some_email",
firstName: "Firstname",
lastName: "Lastname",
groups: [
{id: "2", name: "Manager"},
{id: "10", name: "Remarketing Manager"}
]
}
}
},
{
company: "CompanyName",
id: "2",
userProfile: {
id: "3",
telephone: "",
user: {
email: "some_email",
firstName: "Firstname",
lastName: "Lastname",
groups: [
{id: "1", name: "Seller"}
]
}
}
},
{
company: "CompanyName",
id: "3",
userProfile: {
id: "4",
telephone: "",
user: {
email: "some_email",
firstName: "Firstname",
lastName: "Lastname",
groups: [
{id: "2", name: "Manager"}
]
}
}
}
]
I want to count by group name.
Thus the result that I want is:
{
"Manager": 2,
"Seller": 1,
"Remarketing Manager": 1,
}
I tried with lodash countBy as follows:
countBy(users, 'userProfile.user.groups.name');
But it doesn't work.
Here is the fiddle.
Flatten the arrays of groups with _.flatMap(), and then count by name:
const data = [{"company":"CompanyName","id":"1","userProfile":{"id":"2","telephone":"","user":{"email":"some_email","firstName":"Firstname","lastName":"Lastname","groups":[{"id":"2","name":"Manager"},{"id":"10","name":"Remarketing Manager"}]}}},{"company":"CompanyName","id":"2","userProfile":{"id":"3","telephone":"","user":{"email":"some_email","firstName":"Firstname","lastName":"Lastname","groups":[{"id":"1","name":"Seller"}]}}},{"company":"CompanyName","id":"3","userProfile":{"id":"4","telephone":"","user":{"email":"some_email","firstName":"Firstname","lastName":"Lastname","groups":[{"id":"2","name":"Manager"}]}}}]
const result = _.countBy(_.flatMap(data, 'userProfile.user.groups'), 'name')
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
You can use reduce
let data = [{company: "CompanyName",id: "1",userProfile: {id: "2",telephone: "",user: {email: "some_email",firstName: "Firstname",lastName: "Lastname",groups: [{id: "2", name: "Manager"},{id: "10", name: "Remarketing Manager"}]}}},{company: "CompanyName",id: "2",userProfile: {id: "3",telephone: "",user: {email: "some_email",firstName: "Firstname",lastName: "Lastname",groups: [{id: "1", name: "Seller"}]}}},{company: "CompanyName",id: "3",userProfile: {id: "4",telephone: "",user: {email: "some_email",firstName: "Firstname",lastName: "Lastname",groups: [{id: "2", name: "Manager"}]}}}]
let final = data.reduce((op,{userProfile:{user:{groups}}}) => {
groups.forEach(({name}) => {
op[name] = op[name] || 0
op[name]++
})
return op
},{})
console.log(final)