Javascript - find largest number - javascript

I have a project data that has list of projects and associated employees. Each employee object has salary property. What I'm trying to do is to find the employee with maximum salary.
Example of code:
var projects = [
//Object(0)
{
projectName: "Winter",
projectCode: "O0123",
employee: [{
title: "Mr.",
name: "Tom",
id: 1005,
salary: 12345
},
{
title: "Mr.",
name: "Bunny",
id: 1009,
salary: 54321
},
{
title: "Mr.",
name: "Harris",
id: 1010,
salary: 23456
},
]
},
//Object(1)
{
projectName: "Summer",
projectCode: "P10406",
employee: [{
title: "Mr.",
name: "Seth",
id: 1006,
salary: 1234
},
{
title: "Mr.",
name: "Sam",
id: 1011,
salary: 654321
},
],
}
]
console.log(projects.length);
let maxSalary = 0;
for (var i = 0; i < projects.length; i++) {
console.log(projects[i].projectName);
for (var j = 0; j < projects[i].employee.length; j++) {
console.log("\t" + projects[i].employee[j].title + projects[i].employee[j].name + "\n" + "\t" + "Salary: " + projects[i].employee[j].salary);
if (i == 0 && j == 0) {
maxSalary <= projects[i].employee[j].salary;
}
if (projects[i].employee[j].salary > maxSalary) {
maxSalary = projects[i].employee[j].salary;
}
}
}
console.log("Max Salary = " + maxSalary);
Please suggest any inputs.

Simply loop through the different projects and then loop the employees to get the highest value.
var projects = [{
projectName: "Winter",
projectCode: "O0123",
employee: [
{title: "Mr.", name: "Tom", id: 1005, salary: 12345},
{title: "Mr.", name: "Bunny", id: 1009, salary: 54321},
{title: "Mr.", name: "Harris", id: 1010, salary: 23456}
]
},
{
projectName: "Summer",
projectCode: "P10406",
employee: [
{title: "Mr.", name: "Seth", id: 1006, salary: 1234},
{title: "Mr.", name: "Sam", id: 1011, salary: 654321}
]
}
];
var max = 0;
projects.forEach(p => p.employee.forEach(e => e.salary > max && (max = e.salary)));
console.log(max);
If you want to receive the employee, as you mentioned in your question, and not the salary, you could do it basically the same, just returning the whole object:
var projects = [{
projectName: "Winter",
projectCode: "O0123",
employee: [
{title: "Mr.", name: "Tom", id: 1005, salary: 12345},
{title: "Mr.", name: "Bunny", id: 1009, salary: 54321},
{title: "Mr.", name: "Harris", id: 1010, salary: 23456}
]
},
{
projectName: "Summer",
projectCode: "P10406",
employee: [
{title: "Mr.", name: "Seth", id: 1006, salary: 1234},
{title: "Mr.", name: "Sam", id: 1011, salary: 654321}
]
}
];
var max = {salary: 0};
projects.forEach(p => p.employee.forEach(e => e.salary > max.salary && (max = e)));
console.log(max);
I think these examples will give you a basic idea how to do this.

here you have to mix flatMap which will transform your array of array to simple flat array.
then you can use array reduce to pick up the highest salary.
const projects = [
{
employee: [{
salary: 12345
},
{
salary: 54321
},
{
salary: 23456
},
]
},
{
employee: [{
salary: 1234
},
{
salary: 654321
},
]
}
];
const salaries = projects.flatMap(project => {
// here we have array of array, goal is to craft flat array of salary.
return project.employee.map(employe => {
// From each employee, we pickup only the salary.
return employe.salary;
});
});
const highest = salaries.reduce((accumulator, currentValue) => {
// If current salary is highest than the previous, we keep track of it.
if(currentValue > accumulator) {
accumulator = currentValue;
}
return accumulator;
});

You already have the maximum salary, what you need to do is save the index of the employee with the highest salary as soon as you get it. You code should look like this.
var projects = [
//Object(0)
{
projectName: "Winter",
projectCode: "O0123",
employee: [{
title: "Mr.",
name: "Tom",
id: 1005,
salary: 12345
},
{
title: "Mr.",
name: "Bunny",
id: 1009,
salary: 54321
},
{
title: "Mr.",
name: "Harris",
id: 1010,
salary: 23456
},
]
},
//Object(1)
{
projectName: "Summer",
projectCode: "P10406",
employee: [{
title: "Mr.",
name: "Seth",
id: 1006,
salary: 1234
},
{
title: "Mr.",
name: "Sam",
id: 1011,
salary: 654321
},
],
}
]
console.log(projects.length);
let maxSalary = 0;
let employeeWithMaxSalary = {};
for (var i = 0; i < projects.length; i++) {
console.log(projects[i].projectName);
for (var j = 0; j < projects[i].employee.length; j++) {
console.log("\t" + projects[i].employee[j].title + projects[i].employee[j].name + "\n" + "\t" + "Salary: " + projects[i].employee[j].salary);
if (i == 0 && j == 0) {
maxSalary <= projects[i].employee[j].salary;
}
if (projects[i].employee[j].salary > maxSalary) {
maxSalary = projects[i].employee[j].salary;
employeeWithMaxSalary = projects[i].employee[j];
}
}
}
console.log("Max Salary = " + maxSalary);
console.log(employeeWithMaxSalary);
You can improve also improve your code by using ES6 syntax (arrow function and foreach) instead of having nested loops.

Related

Field value from first Array to get the values from the Second Array in Javascript

I've got two arrays, arr1 has the field and I need to take only the field value from it. The field value should be checked with the arr2 and if it matches the name of the key then need to create as the output below:
let arr1 = [{
field: "name",
value: "some1",
value1: "some2"
},{
field: "job",
value: "some1",
value1: "some2"
},{
field: "from",
value: "some1",
value1: "some3"
}
];
let arr2 = [{
name: "John",
job: "engineer",
address: "abc",
from: "boston",
gender: "male"
},{
name: "Steph",
job: "worker",
address: "uhuh",
from: "uk",
gender: "male"
},{
name: "dor",
job: "farmer",
address: "gdgs",
from: "us",
gender: "female"
}
];
Needed Output:
[{
name: "John",
job: "engineer",
from: "boston"
},{
name: "Steph",
job: "worker",
from: "uk"
},{
name: "Ram",
job: "farmer",
from: "us"
}
];
I tried doing this but I am getting only the last values in arr2.
for(let index = 0; index < arr2.length; index++){
for(let newi = 0; newi < arr1.length; newi++){
newObj = arr1[newi].field;
final[newObj] = arr2[index][newObj]
last.push(final[newObj])
}
console.log(last)
}
Do it like this, using Array.map & Array.reduce
const arr1 = [{ field: "name", value: "some1", value1: "some2"},{ field: "job", value: "some1", value1: "some2"},{ field: "from", value: "some1", value1: "some3"}];
const arr2 = [{ name: "John", job: "engineer", address: "abc", from: "boston", gender: "male"},{ name: "Steph", job: "worker", address: "uhuh", from: "uk", gender: "male"},{ name: "dor", job: "farmer", address: "gdgs", from: "us", gender: "female"}];
const result = arr2.map(item => arr1.reduce((acc, {field}) => {
acc[field] = item[field];
return acc;
}, {}));
console.log(result);
Using map and Object.assign
const arr1 = [{ field: "name", value: "some1", value1: "some2"},{ field: "job", value: "some1", value1: "some2"},{ field: "from", value: "some1", value1: "some3"}];
const arr2 = [{ name: "John", job: "engineer", address: "abc", from: "boston", gender: "male"},{ name: "Steph", job: "worker", address: "uhuh", from: "uk", gender: "male"},{ name: "dor", job: "farmer", address: "gdgs", from: "us", gender: "female"}];
const fields = arr1.map(({ field }) => field);
const output = arr2.map((item) =>
Object.assign({}, ...fields.map((field) => ({ [field]: item[field] })))
);
console.log(output)

How to get duplicate elements in an array

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

Map two separate arrays by matching object keys to values

Been scratching my head on this one for an entire evening with no solution in sight.
Put simply
I am querying two arrays from two separate APIs.
They return data in following format:
API 1
[{
balance: 4444,
age: "18",
gender: "Male",
level: "2",
name: "Joe"
}, {
balance: 3333,
age: "45",
gender: "Male",
level: "3",
name: "Angel"
}
}]
API 2
{
Joe: {
score: 32
},
Angel: {
score: 22
}
}
I need to match the object keys from the second API to the name value of playerInfo from first API so a new array is made that is completely flat like this:
[{
balance: 4444,
age: "18",
gender: "Male",
level: "2",
name: "Joe",
score: 32
}, {
balance: 3333,
age: "45",
gender: "Male",
level: "3",
name: "Angel",
score: 22
}
}]
Here's where I am being stone walled at the moment
var result = []
const matchKeys = (data, data1) => {
let arr = []
arr.push(data1)
data.map(item => {
arr.map(item1 => {
if (item.name === Object.keys(item1)) {
result.push(Object.assign(item, item1))
console.log(result)
}
})
})
}
matchKeys(api1, api2)
I suspect I'm not getting very far because I am not properly accessing my second dataset because there is no index that keeps track of which object I am supposed to pair up with corresponding value in the arrays.
Appreciate any help
You can implement that using Array.map.
const input1 = [{
balance: 4444,
age: "18",
gender: "Male",
level: "2",
name: "Joe"
}, {
balance: 3333,
age: "45",
gender: "Male",
level: "3",
name: "Angel"
}];
const input2 = {
Joe: {
score: 32
},
Angel: {
score: 22
}
}
function matchKeys(arr1, arr2) {
const result = arr1.map((item) => {
if (input2[item.name]) {
return { ...item, ...input2[item.name] };
}
return item;
});
return result;
}
console.log(matchKeys(input1, input2));
you could use the property of the second object as a way to search the right name.
const input1 = [{
balance: 4444,
age: "18",
gender: "Male",
level: "2",
name: "Joe"
}, {
balance: 3333,
age: "45",
gender: "Male",
level: "3",
name: "Angel"
}];
const input2 = {
Joe: {
score: 32
},
Angel: {
score: 22
}
}
const matchKeys = (data, data1) => {
return data.map((item) => ({ ...item, score: data1[item.name] ? data1[item.name].score : 0 }));
}
console.log(matchKeys(input1, input2));
also checked if it has a name and if for some reason it didn't I inserted a default score.

Filtering a nested array with objects by checking another nested array with object - JavaScript

I have an array like this:
const state = {
products: [
{ name: "Potato", amount: "3"},
{ name: "Butter", amount: "1000" },
{ name: "Salt", amount: "2000" },
//{name: "Egg", amount: "10"},
{ name: "Tomato", amount: "5"},
{ name: "Sour Milk", amount: "5"}
],
recipes: [
{
name: "Mashed potatoes",
ingredients: [
{ name: "Potato", amount: "5"},
{ name: "Butter", amount: "30"},
{ name: "Salt", amount: "15"}
],
instructions: "Some Text"
},
{
name: "Tomato Omelette",
ingredients: [
{ name: "Tomato", amount: "1" },
{ name: "Egg", amount: "1" },
{ name: "Salt", amount: "10" },
{ name: "Butter", amount: "40" }
],
instructions: "Some text"
}
]
};
I want to filter my recipes array by recipes that I can cook with my products (in this case I can't cook "Tomato omelette" because I don't have any eggs and I can't cook "Mashed Potatoes" because I don't have enough potatoes).
So far I tried different approaches but I didn't come up with a whole solution.
My closest solution was this:
const filterRecipes = (filter, products, recipes) => {
if(filter === 'available products') {
//Getting all product names for future tests
const productsNames = products.map(item => item.name);
//Here we will filter all our recipes by available products
const result = recipes.filter(recipe => {
//Getting all ingredient names of the current recipe
const ingredientNames = recipe.ingredients.map(item => item.name);
//If we have all products for our recipe
//we will add it to our filtered array
if (ingredientNames.every((name) => productsNames.includes(name))){
return true;
}
})
console.log(result);
}
};
This one works only for the names of the products but not for its amount. When I'm trying to check for the amount it just brokes.
Here is the whole code:
const state = {
products: [
{ name: "Potato", amount: "5"},
{ name: "Butter", amount: "1000" },
{ name: "Salt", amount: "2000" },
//{name: "Egg", amount: "10"},
{ name: "Tomato", amount: "5"},
{ name: "Sour Milk", amount: "5"}
],
recipes: [
{
name: "Mashed potatoes",
ingredients: [
{ name: "Potato", amount: "5"},
{ name: "Butter", amount: "30"},
{ name: "Salt", amount: "15"}
],
instructions: "Some Text"
},
{
name: "Tomato Omelette",
ingredients: [
{ name: "Tomato", amount: "1" },
{ name: "Egg", amount: "1" },
{ name: "Salt", amount: "10" },
{ name: "Butter", amount: "40" }
],
instructions: "Some text"
}
]
};
const filterRecipes = (filter, products, recipes) => {
if(filter === 'available products') {
//Getting all product names for future tests
const productsNames = products.map(item => item.name);
//Here we will filter all our recipes by available products
const result = recipes.filter(recipe => {
//Getting all ingredient names of the current recipe
const ingredientNames = recipe.ingredients.map(item => item.name);
//If we have all products for our recipe
//we will add it to our filtered array
if (ingredientNames.every((name) => productsNames.includes(name))){
return true;
}
})
console.log(result);
}
};
filterRecipes("available products", state.products, state.recipes);
We can do it like this:
Set up a productsObj with reduce to allow fast lookups
filter the recipes array
inside each callback of the recipes filter function, and loop over ingredients of each recipe
for each ingredient, check it exists in productsObj and the amount is larger than or equal to the item in the recipe ingredients.
if it is present and with large enough qty keep checking the rest of the ingredients
if not, return false - i.e. filter out of array.
const state = {
products: [
{ name: "Potato", amount: "5" },
{ name: "Butter", amount: "1000" },
{ name: "Salt", amount: "2000" },
{ name: "Egg", amount: "10" },
{ name: "Tomato", amount: "5" },
{ name: "Sour Milk", amount: "5" }
],
recipes: [
{
name: "Mashed potatoes",
ingredients: [
{ name: "Potato", amount: "5" },
{ name: "Butter", amount: "30" },
{ name: "Salt", amount: "15" }
],
instructions: "Some Text"
},
{
name: "Tomato Omelette",
ingredients: [
{ name: "Tomato", amount: "1" },
{ name: "Egg", amount: "1" },
{ name: "Salt", amount: "10" },
{ name: "Butter", amount: "40" }
],
instructions: "Some text"
}
]
};
const filterRecipes = (filter, products, recipes) => {
if (filter === "available products") {
//Getting all product names in an object for fast look-up
const productsObj = products.reduce((aggObj, item) => {
aggObj[item.name] = item;
return aggObj;
}, {});
//console.log("o", productsObj);
//Here we will filter all our recipes by available products
const result = recipes.filter((recipe) => {
let valid = true; //true until proven false
//Loop over ingredients of each recipe
for (let i = 0; i < recipe.ingredients.length; i++) {
const item = recipe.ingredients[i];
const lookup = productsObj[item.name] || false;
const quantityEnough = lookup
? parseInt(lookup.amount) >= parseInt(item.amount)
: false;
if (!quantityEnough) {
valid = false;
break;
}
}
return valid;
});
console.log(result);
}
};
filterRecipes("available products", state.products, state.recipes);
.as-console-wrapper { max-height: 100% !important; top: 0; }
For example if you change your product quantitiess to:
const state = {
products: [
{ name: "Potato", amount: "4" },
{ name: "Butter", amount: "1000" },
{ name: "Salt", amount: "2" },
{ name: "Egg", amount: "10" },
{ name: "Tomato", amount: "5" },
{ name: "Sour Milk", amount: "5" }
],
You get no results as salt and potatoes quantities are not large enough for either recipe.
You could take an object for faster access, with amount as numbers for better comparability
{
Potato: 5,
Butter: 1000,
Salt: 2000,
Tomato: 5,
"Sour Milk": 5
}
and loop only products and recieps once.
This approach uses destructuring assignment, where properties are taken out of objects.
The it uses the value of the object and checks the available amount for all ingredients.
const
filter = ({ products, recipes }) => {
const avalilable = products.reduce((r, { name, amount }) => (r[name] = +amount, r), {});
console.log(avalilable )
return recipes.filter(({ ingredients }) =>
ingredients.every(({ name, amount }) => avalilable[name] >= +amount));
},
state = { products: [{ name: "Potato", amount: "5" }, { name: "Butter", amount: "1000" }, { name: "Salt", amount: "2000" }, { name: "Tomato", amount: "5" }, { name: "Sour Milk", amount: "5" }], recipes: [{ name: "Mashed potatoes", ingredients: [{ name: "Potato", amount: "5" }, { name: "Butter", amount: "30" }, { name: "Salt", amount: "15" }], instructions: "Some Text" }, { name: "Tomato Omelette", ingredients: [{ name: "Tomato", amount: "1" }, { name: "Egg", amount: "1" }, { name: "Salt", amount: "10" }, { name: "Butter", amount: "40" }], instructions: "Some text" }] },
recipes = filter(state);
console.log(recipes);
You can try this solution.
Here I add a solution to a situation say, you have 20 units of "salt" and the first recipe takes 15 units of them for cooking.
Now assume, the second recipe needs 10 units of salt but you have 5 units left at your store. In this situation, you cannot take the
second recipe for cooking.
const state = {
products: [
{ name: "Potato", amount: "5"},
{ name: "Butter", amount: "1000" },
{ name: "Salt", amount: "20" },
{ name: "Egg", amount: "1"},
{ name: "Tomato", amount: "5"},
{ name: "Sour Milk", amount: "5"}
],
recipes: [
{
name: "Mashed potatoes",
ingredients: [
{ name: "Potato", amount: "5"},
{ name: "Butter", amount: "30"},
{ name: "Salt", amount: "15"}
],
instructions: "Some Text"
},
{
name: "Tomato Omelette",
ingredients: [
{ name: "Tomato", amount: "1" },
{ name: "Egg", amount: "1" },
{ name: "Salt", amount: "10" },
{ name: "Butter", amount: "40" }
],
instructions: "Some text"
}
]
};
const filterRecipes = (filter, products, recipes) => {
if (filter === 'available products') {
/**
* Restructure the products from array to object.
* like {Potato: "20", "Salt": "200"}
*/
const store = products.reduce((a, {name, amount}) => {
return {...a, [name]: amount};
}, {});
const canCook = recipes.filter(recipe => {
/**
* Convert ingredient from array to object like products
*
*/
const ingredients = recipe.ingredients.reduce((a, {name, amount}) => {
return {...a, [name]: amount};
}, {});
/**
* Check if every ingredients are available at the store
*/
const allow = Object.entries(ingredients).every(([name, amount]) => {
return (store[name] !== undefined && (+store[name]) >= (+amount));
});
/**
* This is for reducing the amount of ingredient from the store
* if the recipe is taken for cooking.
* You can omit it if you don't need to measure this factor.
*/
if (allow) {
Object.entries(ingredients).forEach(([name, amount]) => {
store[name] -= amount;
});
}
return allow;
});
console.log(canCook);
}
}
filterRecipes("available products", state.products, state.recipes);
.as-console-wrapper {min-height: 100% !important; top: 0;}

How to merge the property with same key in two object array?

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);

Categories

Resources