Making occurrence of object in array a property - javascript

I'm trying to add a new property to multiple objects in a array that counts its occurrence. The current function can delete duplicated objects but cannot count how many times it is repeated.
const artists = [
{ name: 'Paul', age: '18', 'id': 1 },
{ name: 'Joseph', age: '21', 'id': 2 },
{ name: 'Maggie', age: '20', 'id': 3 },
{ name: 'Paul', age: '18', 'id': 1 },
{ name: 'Maggie', age: '20', 'id': 3 },
{ name: 'John', age: '18', 'id': 4 },
{ name: 'Joseph', age: '21', 'id': 2 },
{ name: 'Tenner', age: '30', 'id': 5 },
{ name: 'Maggie', age: '20', 'id': 3 },
]
const countOccurrence = (arr) => {
let uniqueArray = []
uniqueArray = arr.filter(item => {
item['occurrence'] = ++item['occurrence'] || 1
if (!uniqueArray.includes(item.id)) {
uniqueArray.push(item.id)
return true
}
})
return uniqueArray
}
let uniqueArtists = countOccurrence(artists)
console.log(uniqueArtists)
I'm getting:
[
{ name: 'Paul', age: '18', id: 1, occurrence: 1 },
{ name: 'Joseph', age: '21', id: 2, occurrence: 1 },
{ name: 'Maggie', age: '20', id: 3, occurrence: 1 },
{ name: 'John', age: '18', id: 4, occurrence: 1 },
{ name: 'Tenner', age: '30', id: 5, occurrence: 1 }
]
I'm trying to get:
[
{ name: 'Paul', age: '18', id: 1, occurrence: 2 },
{ name: 'Joseph', age: '21', id: 2, occurrence: 2 },
{ name: 'Maggie', age: '20', id: 3, occurrence: 3 },
{ name: 'John', age: '18', id: 4, occurrence: 1 },
{ name: 'Tenner', age: '30', id: 5, occurrence: 1 }
]
The order does not matter, I'm just trying to get the right occurrence values.

You could take a hash table and increment the occurence for each grouped worker.
This approach does not mutate the original data.
const
workers = [{ name: 'Paul', age: '18', id: 1 }, { name: 'Joseph', age: '21', id: 2 }, { name: 'Maggie', age: '20', id: 3 }, { name: 'Paul', age: '18', id: 1 }, { name: 'Maggie', age: '20', id: 3 }, { name: 'John', age: '18', id: 4 }, { name: 'Joseph', age: '21', id: 2 }, { name: 'Tenner', age: '30', id: 5 }, { name: 'Maggie', age: '20', id: 3 }],
countOccurrence = (arr) => {
let uniqueArray = [],
hashTable = {}
arr.forEach(item => {
if (!hashTable[item.id]) {
uniqueArray.push(hashTable[item.id] = { ...item, occurrence: 0 });
}
hashTable[item.id].occurrence++;
});
return uniqueArray;
},
uniqueArtists = countOccurrence(workers);
console.log(uniqueArtists);
.as-console-wrapper { max-height: 100% !important; top: 0; }
A slightly different approach by using an object and getting the values as return array.
const
workers = [{ name: 'Paul', age: '18', id: 1 }, { name: 'Joseph', age: '21', id: 2 }, { name: 'Maggie', age: '20', id: 3 }, { name: 'Paul', age: '18', id: 1 }, { name: 'Maggie', age: '20', id: 3 }, { name: 'John', age: '18', id: 4 }, { name: 'Joseph', age: '21', id: 2 }, { name: 'Tenner', age: '30', id: 5 }, { name: 'Maggie', age: '20', id: 3 }],
countOccurrence = (arr) => {
let hashTable = {}
arr.forEach(item => {
if (!hashTable[item.id]) {
hashTable[item.id] = { ...item, occurrence: 0 };
}
hashTable[item.id].occurrence++;
});
return Object.values(hashTable);
},
uniqueArtists = countOccurrence(workers);
console.log(uniqueArtists);
.as-console-wrapper { max-height: 100% !important; top: 0; }

The problem with your approach is that while you update each item in your filter, you're updating only the current iterated value, and then including it in the output (by returning true to filter) only in the case that you haven't already seen its id. So as you go through, you update the occurrence of each one to 1, but then ignore the duplicates. You need to somehow track these by id.
You can do this in a single reduce call, wrapped in Object .values, like this:
const countOccurrences = xs => Object .values (xs .reduce ((
a, x, _i , _arr, // last two unused
{occurrences, ...rest} = x .id in a ? a [x .id] : {...x, occurrences: 0}
) => ({
... a,
[x .id] : {...rest, occurrences: occurrences + 1}
}), {}))
const workers = [ { name: 'Paul', age: '18', 'id': 1 }, { name: 'Joseph', age: '21', 'id': 2 }, { name: 'Maggie', age: '20', 'id': 3 }, { name: 'Paul', age: '18', 'id': 1 }, { name: 'Maggie', age: '20', 'id': 3 }, { name: 'John', age: '18', 'id': 4 }, { name: 'Joseph', age: '21', 'id': 2 }, { name: 'Tenner', age: '30', 'id': 5 }, { name: 'Maggie', age: '20', 'id': 3 } ]
console .log (
countOccurrences (workers)
)
.as-console-wrapper {min-height: 100% !important; top:0}
Note that this does not mutate your original data.
It also does not mutate the accumulator used in the reduce call or its properties. That can occasionally be a performance problem. If your data sets are large or if you're doing this often, you might want to change from this style of immutable accumulator objects to one that mutates the internal accumulator and its values as you go. Rich Snapp has an excellent article describing the reasons for this. But if this performance is acceptable, then I wouldn't bother, as I find this cleaner.

Related

How does one, from an array of objects, collect and aggregate the merged variant of all objects with a specific equal property value?

const portfolio = [
{ name: 'Mark', stock: 'FB' },
{ name: 'Steve', stock: 'AAPL' },
{ name: 'Tim', stock: 'AAPL' },
{ name: 'Steve', stock: 'MSFT' },
{ name: 'Bill', stock: 'MSFT' },
{ name: 'Bill', stock: 'AAPL' },
];
// Output
const shareholder = [
{ stock: 'AAPL', name: ['Steve', 'Bill', 'Tim'], count: 3 },
{ stock: 'MSFT', name: ['Steve', 'Bill'], count: 2 },
{ stock: 'FB', name: ['Mark'], count: 1 },
];
if I create one function which take input array as param and this will return output array in jS
One way using reduce and Object.values
const portfolio = [{
name: 'Mark',
stock: 'FB'
},
{
name: 'Steve',
stock: 'AAPL'
},
{
name: 'Tim',
stock: 'AAPL'
},
{
name: 'Steve',
stock: 'MSFT'
},
{
name: 'Bill',
stock: 'MSFT'
},
{
name: 'Bill',
stock: 'AAPL'
},
];
const result = Object.values(portfolio.reduce((res, {
stock,
name
}) => {
const existing = res[stock] || {
stock,
names: [],
count: 0
}
res[stock] = {
stock,
names: [...existing.names, name],
count: existing.count + 1
}
return res
}, {}))
console.log(result)
From the above comment ...
"What the OP wants is filtering and grouping array items (by a specific key) together with value aggregation of some/one other key/s. One usually would use a reduce based approach. One question though ... what is the additional count value good for when one has this information already in any item's item.name.length (or at least rename count to nameCount)."
... used techniques/methods ...
Object.values
Array.prototype.reduce
Array.prototype.sort
Destructuring Assignment / object destructuring
Logical nullish assignment operator / ??=
const portfolio = [
{ name: 'Mark', stock: 'FB' },
{ name: 'Steve', stock: 'AAPL' },
{ name: 'Tim', stock: 'AAPL' },
{ name: 'Steve', stock: 'MSFT' },
{ name: 'Bill', stock: 'MSFT' },
{ name: 'Bill', stock: 'AAPL' },
];
const shareholderList = Object.values( // get only the values from ...
// ... create an index/map of stock specific shareholder items/objects
portfolio.reduce((stockIndex, { name, stock }) => {
// access an already existing object or
// create a new grouped (by `stock` value) to be merged and aggregated object.
const groupedMerger = (stockIndex[stock] ??= { stock, names: [], nameCount: 0 });
// aggregate list of `stock` specific shareholder names.
groupedMerger.names.push(name);
// increment count of `stock` specific shareholder names.
++groupedMerger.nameCount;
// the programmatically built index/map of stock specific shareholder items/objects.
return stockIndex;
}, {})
).sort((a, b) => b.nameCount - a.nameCount); // sort shareholder items by theirs `nameCount`s.
console.log({ shareholderList });
.as-console-wrapper { min-height: 100%!important; top: 0; }
And in order to demonstrate how each part works and how everything works together, the above main approach will be compacted into a (re-usable) function statement.
function aggregateStockIndex(index, { name, stock }) {
const groupedMerger = (index[stock] ??= { stock, names: [], nameCount: 0 });
groupedMerger.names.push(name);
++groupedMerger.nameCount;
return index;
}
const portfolio = [
{ name: 'Mark', stock: 'FB' },
{ name: 'Steve', stock: 'AAPL' },
{ name: 'Tim', stock: 'AAPL' },
{ name: 'Steve', stock: 'MSFT' },
{ name: 'Bill', stock: 'MSFT' },
{ name: 'Bill', stock: 'AAPL' },
];
const stockIndex = portfolio
.reduce(aggregateStockIndex, {});
const shareholderList = Object.values(
// stockIndex
portfolio.reduce(aggregateStockIndex, {})
).sort((a, b) => b.nameCount - a.nameCount);
console.log({
stockIndex,
shareholderList,
});
.as-console-wrapper { min-height: 100%!important; top: 0; }
I shared a function named groupPortfolio that takes a portfolio as an argument expecting to be a list of people holding a share of a stock.
The function first groups those people as a map binding each stock to which holders it belong to and eventually uses that map to create the final array as a list of stocks where each one has a list of people holding its share and the corresponding amount of people in that list.
function groupPortfolio(portfolio){
//groups the portfolio item in [stock] => shareholders[]
let grouped = {};
for(let o of portfolio){
if( !Object.keys(grouped).includes(o.stock) )
grouped[o.stock] = [];
grouped[o.stock].push( o.name );
}
//creates the shareholders array starting from the grouped stocks
let shareholders = [];
for( let stockGroup of Object.keys(grouped) ){
shareholders.push(
{ stock: stockGroup, name: grouped[stockGroup], count: grouped[stockGroup].length }
);
}
return shareholders;
}
const portfolio1 = [
{name: 'Mark', stock: 'FB'},
{name: 'Steve', stock: 'AAPL'},
{name: 'Tim', stock: 'AAPL'},
{name: 'Steve', stock: 'MSFT'},
{name: 'Bill', stock: 'MSFT'},
{name: 'Bill', stock: 'AAPL'},
];
let shareholder1 = groupPortfolio(portfolio1);
console.log( shareholder1 );
/*
0:
stock: "FB"
name: ['Mark']
count: 1
1:
stock: "AAPL"
name: (3) ['Steve', 'Tim', 'Bill']
count: 3
2:
stock: "MSFT"
name: (2) ['Steve', 'Bill']
count: 2
*/
You can use two simple for loops to convert the first array into the second array.
Working Example:
const portfolio = [
{name: 'Mark', stock: 'FB'},
{name: 'Steve', stock: 'AAPL'},
{name: 'Tim', stock: 'AAPL'},
{name: 'Steve', stock: 'MSFT'},
{name: 'Bill', stock: 'MSFT'},
{name: 'Bill', stock: 'AAPL'},
];
let shareholder = [];
// CYCLE THROUGH PORTFOLIO
for (let i = 0; i < portfolio.length; i++) {
// DETERMINE IF STOCK ENTRY ALREADY EXISTS
let stockIndex = shareholder.length;
for (let j = 0; j < shareholder.length; j++) {
if (portfolio[i].stock === shareholder[j].stock) {
stockIndex = j;
}
}
// ADD NEW ENTRY IF STOCK ENTRY DOES NOT EXIST
if (stockIndex === shareholder.length) {
shareholder[stockIndex] = {stock: portfolio[i].stock, name: [], count: 0};
}
// ADD DETAILS TO NEW OR EXISTING STOCK ENTRY
shareholder[stockIndex].name.push(portfolio[i].name);
shareholder[stockIndex].count++;
}
console.log(shareholder);
You could achieve this in two steps
First create an object with stock as the key name to find out all the records with unique stock.
Loop over the object created in step#1 to convert to an Array structure
I couldn't think of ay solution which could achieve it in single iteration.
Please see the code snippet below.
const portfolio = [
{name: 'Mark', stock: 'FB'},
{name: 'Steve', stock: 'AAPL'},
{name: 'Tim', stock: 'AAPL'},
{name: 'Steve', stock: 'MSFT'},
{name: 'Bill', stock: 'MSFT'},
{name: 'Bill', stock: 'AAPL'},
];
let shareholderObj = {};
let shareholderArr = [];
portfolio.forEach((el) => {
const stock = el.stock
if(shareholderObj[stock]){
shareholderObj[stock].name.push(el.name)
}
else{
shareholderObj[stock] = {
name: [el.name]
}
}
})
for (let [key, value] of Object.entries(shareholderObj)) {
shareholderArr.push({
stock: key,
name: value.name,
count: value.name.length
})
}
console.log(shareholderArr)
A simplified approach by taking the new length of name as count.
const portfolio = [{ name: 'Mark', stock: 'FB' }, { name: 'Steve', stock: 'AAPL' }, { name: 'Tim', stock: 'AAPL' }, { name: 'Steve', stock: 'MSFT' }, { name: 'Bill', stock: 'MSFT' }, { name: 'Bill', stock: 'AAPL' }],
shareholder = Object
.values(portfolio.reduce((r, { name, stock }) => {
r[stock] ??= { stock, name: [] };
r[stock].count = r[stock].name.push(name);
return r;
}, {}))
.sort((a, b) => b.count - a.count)
console.log(shareholder);
.as-console-wrapper { max-height: 100% !important; top: 0; }

JS - merge 2 arrays based on properties

I'm trying to merge 2 arrays of objects where the resulting array should have only objects present in array 1 (selectedNames) but with one property from corresponding objects from array 2 (nameDetails). There's one matching (unique) property to match them:
const selectedNames = [
{
id: '11'
name: 'joe',
},
{
id: '22',
name: 'bill',
},
];
const nameDetails = [
{
nameId: '11',
salary: '23422',
location: 'New Jersey',
},
{
nameId: '33',
salary: '23424',
location: 'New York',
},
{
nameId: '22',
salary: '99999',
location: 'Boston',
},
{ nameId: '44',
salary: '323232',
location: 'Chicago',
},
];
The matching property is selectedNames.id === nameDetails.nameId. All entries in selectedNames will definitely be present in nameDetails (but not the other way round). The resulting array should look like that:
[
{
id: '11',
name: 'joe',
salary: '23422',
},
{
id: '22',
name: 'bill',
salary: '99999'
}
]
I'm a bit confused. I know it'll probably consist of .includes() and filter() and ... for merging? I'm not sure how to handle it.
Alternatively, which will probably be much easier, filter the nameDetails array to have only objects with nameId that exists (as id) in selectedNames.
I am a bit confused by your example result. For example where does id: '11111' come from?
Are you looking for something like this maybe?
const selectedNames = [
{
id: '11',
name: 'joe',
},
{
id: '22',
name: 'bill',
},
];
const nameDetails = [
{
nameId: '11',
salary: '23422',
location: 'New Jersey',
},
{
nameId: '33',
salary: '23424',
location: 'New York',
},
{
nameId: '22',
salary: '99999',
location: 'Boston',
},
{ nameId: '44',
salary: '323232',
location: 'Chicago',
},
];
const merged = selectedNames.map(n => {
n.salary = nameDetails.filter(d => n.id === d.nameId)[0].salary;
return n;
});
console.log(merged)
Note: This will change the original selectedNames by adding the salary from the corresponding entry in nameDetails.
Maybe this fits your needs:
selectedNames.map(({ id, name }) => {
let salary = nameDetails.find((nameItem) => nameItem.nameId === id).salary;
return { id, name, salary };
})
Will result in:
[
{
id: '11',
name: 'joe',
salary: '23422',
},
{
id: '22',
name: 'bill',
salary: '99999',
}
]

Replace the records of particular category

There is one scenario where i need to replace the existing records from cached data with new incoming data source. Looking for the cleaner approach to handle the array operations.
For example:
var userCategory = [
{
id: 'platinum',
name: 'bob',
},
{
id: 'platinum',
name: 'bar',
},
{
id: 'platinum',
name: 'foo',
},
{
id: 'gold',
name: 'tom',
},
{
id: 'silver',
name: 'billy',
},
];
Here is new users of particular category
var newPlatinumUsers = [
{
id: 'platinum',
name: 'bob',
},
{
id: 'platinum',
name: 'mike',
},
];
This is the expected result needed:
var expected = [
{
id: 'platinum',
name: 'bob',
},
{
id: 'platinum',
name: 'mike',
},
{
id: 'gold',
name: 'tom',
},
{
id: 'silver',
name: 'billy',
},
];
I tried with filtering all the platinum user from existing records then added the new records but it looks verbose
Is there any cleaner approach like lodash operator??
Thanks for your time!!!
May you are looking for this.
function getUnique(arr){
// removing duplicate
let uniqueArr = [...new Set(arr)];
document.write(uniqueArr);
}
const array = ['acer','HP','Apple','Apple','something'];
// calling the function
getUnique(array);
Verify my answer if it help you.
Please find the Javascript implementation of the same
var userCategory = [
{ id: 'platinum', name: 'bob', },
{ id: 'platinum', name: 'bar', },
{ id: 'platinum', name: 'foo', },
{ id: 'gold', name: 'tom', },
{ id: 'silver', name: 'billy', },
];
var newPlatinumUsers = [
{ id: 'platinum', name: 'bob', },
{ id: 'platinum', name: 'mike', },
];
const result = [...newPlatinumUsers];
userCategory.forEach((node) => {
if(node.id !== 'platinum') {
result.push(node);
}
});
console.log(result);
With this solution you can change more than one category:
var userCategory = [
{id: 'platinum',name: 'bob'},
{id: 'platinum',name: 'bar'},
{id: 'platinum',name: 'foo'},
{id: 'gold',name: 'tom'},
{id: 'silver',name: 'billy'},
];
var newUsers = [
{id: 'platinum',name: 'bob'},
{id: 'platinum',name: 'mike'},
{id: 'gold',name: 'will'},
{id: 'gold',name: 'jerry'},
];
const idsToReplace = {}
const result = [...newUsers]
result.forEach(u => {
idsToReplace[u.id] = true
})
userCategory.forEach(u => {
if(!idsToReplace[u.id]){
result.push(u)
}
})
console.log(result)

How can I regroup Array of objects by given field

I have given array of objects, something like this
const data = [
{id: 1, name: 'Alex', job: 'IT'},
{id: 2, name: 'Pavel', job: 'IT'},
{id: 3, name: 'Joe', job: 'IT'},
{id: 4, name: 'Josh', job: 'IT'},
{id: 5, name: 'Max', job: 'teacher'},
{id: 6, name: 'Sam', job: 'teacher'}
]
I need array of arrays filtered by field job
const result = [
{job: 'IT',
workersInfo: [
{id:1, name:'Alex'},
{id:2, name:'Pavel'},
{id:3, name:'Joe'},
{id:4, name:'Josh'}
]
},
{job: 'teacher',
workersInfo: [
{id:5, name: 'Max'},
{id:6, name: 'Sam'}
]
}
]
I tried this, but It's not what I want
const data = [
{id: 1, name: 'Alex', job: 'IT'},
{id: 2, name: 'Pavel', job: 'IT'},
{id: 3, name: 'Joe', job: 'IT'},
{id: 4, name: 'Josh', job: 'IT'},
{id: 5, name: 'Max', job: 'teacher'},
{id: 6, name: 'Sam', job: 'teacher'}
]
const groupList = data.reduce((reduce, it) => {
reduce[it.job] = reduce[it.job] || [];
reduce[it.job].push({id: it.id, name: it.name});
return reduce;
}, {})
console.log(Object.values(groupList));
How can I add new key workers Info and push info to this field
If you create a new object on each iteration instead of an array you can then use Object.values:
const data = [
{id: 1, name: 'Alex', job: 'IT'},
{id: 2, name: 'Pavel', job: 'IT'},
{id: 3, name: 'Joe', job: 'IT'},
{id: 4, name: 'Josh', job: 'IT'},
{id: 5, name: 'Max', job: 'teacher'},
{id: 6, name: 'Sam', job: 'teacher'}
];
const groupList = data.reduce((acc, { job, id, name }) => {
acc[job] = acc[job] || { job, workersInfo: [] };
acc[job].workersInfo.push({ id, name });
return acc;
}, {})
console.log(Object.values(groupList));
Example below
const data = [
{ id: 1, name: "Alex", job: "IT" },
{ id: 2, name: "Pavel", job: "IT" },
{ id: 3, name: "Joe", job: "IT" },
{ id: 4, name: "Josh", job: "IT" },
{ id: 5, name: "Max", job: "teacher" },
{ id: 6, name: "Sam", job: "teacher" },
];
const output = data.reduce((acc, o) => {
const index = acc.findIndex(a => a.job === o.job);
if (index !== -1) {
acc[index].workersInfo.push({ id: o.id, name: o.name });
} else {
acc.push({
job: o.job,
workersInfo: [{ id: o.id, name: o.name }],
});
}
return acc;
}, []);
console.log(output);
Would something like this work ?
const groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
console.log(groupBy(['one', 'two', 'three'], 'length'));
// => {3: ["one", "two"], 5: ["three"]}```
It would be more efficient and comprehensible if instead of having a structure like Array<{job: string, workForce: Array}>, you had something like {[job: string]: Array}
var data = [
{ id: 1, name: 'Alex', job: 'IT' },
{ id: 2, name: 'Pavel', job: 'IT' },
{ id: 3, name: 'Joe', job: 'IT' },
{ id: 4, name: 'Josh', job: 'IT' },
{ id: 5, name: 'Max', job: 'teacher' },
{ id: 6, name: 'Sam', job: 'teacher' }
];
var jobs = data.reduce(function (result, person) {
var jobList = result[person.job];
if (!jobList) {
jobList = [];
result[person.job] = jobList;
}
jobList.push(person);
return result;
}, {});
console.log(jobs);

Merge two array of objects based on matching properties

I've 2 arrays with partial information and I wish to merge those arrays with all the information into one array.
Array 1 :
const arr1 = [
{
name: 'Rohan',
surname: 'Mehra',
age: '15',
date: "2021-01-19",
location: 'Goa'
},
{
name: 'Aman',
surname: 'Kohli',
age: '14',
date: "2021-01-19",
location: 'Kolkata'
},
{
name: 'Sam',
surname: 'Sharma',
age: '16',
date: "2021-01-21",
location: 'Mumbai'
}
]
Array 2 :
const arr2 = [
{
rollNo: 1,
marks: 100,
name: 'Rohan',
date: "2021-01-19",
},
{
rollNo: 2,
marks: 90,
surname: 'Kohli',
date: "2021-01-19",
},
{
rollNo: 3,
marks: 70,
date: "2021-01-21",
ExamCenter: {
place: 'Mumbai'
}
}
]
I want to get a final array with the properties from both arrays. The Object keys sometimes change and I wanted to match the key with the other common key and merge them. But I am not able to proceed with the solution. Here is the result array I wish to get.
const final = [
{
name: 'Rohan',
surname: 'Mehra',
age: '15',
date: "2021-01-19",
location: 'Goa',
rollNo: 1,
marks: 100,
},
{
name: 'Aman',
surname: 'Kohli',
age: '14',
date: "2021-01-19",
location: 'Kolkata',
rollNo: 2,
marks: 90,
},
{
name: 'Sam',
surname: 'Sharma',
age: '16',
date: "2021-01-21",
location: 'Mumbai',
rollNo: 3,
marks: 70,
}
]
I'm trying with nested map loops but not able to proceed
const final = arr1.map((item,index) => {
arr2.map((innerItem, i) => {
if(item[Object.keys(innerItem)][index] === innerItem[Object.keys(innerItem)][0]){
console.log(item);
}
})
})
There is a mistake in your arr2. The surname for 2nd item should be kohli instead of kolhi. Anyway, You can do the following to merge two array based on dynamic matching attribute. What we are doing here is,
For each item of arr1 we are finding the keys using Object.keys method and checking which object from arr2 has maximum matching object with the item of arr1. Then we merge the two item together.
arr1 = [
{
name: 'Rohan',
surname: 'Mehra',
age: '15',
date: "2021-01-19",
location: 'Goa'
},
{
name: 'Aman',
surname: 'Kohli',
age: '14',
date: "2021-01-19",
location: 'Kolkata'
},
{
name: 'Sam',
surname: 'Sharma',
age: '16',
date: "2021-01-21",
location: 'Mumbai'
}
]
arr2 = [
{
rollNo: 1,
marks: 100,
name: 'Rohan',
date: "2021-01-19",
},
{
rollNo: 2,
marks: 90,
surname: 'Kohli',
date: "2021-01-19",
},
{
rollNo: 3,
marks: 70,
date: "2021-01-21",
ExamCenter: {
place: 'Mumbai'
}
}
]
res = arr1.map(item => {
keys1 = Object.keys(item);
let max = 0;
const temp = arr2.reduce((prev, item2) => {
maxTemp = keys1.filter(key => item[key] === item2[key]).length;
if(maxTemp > max) {
max = maxTemp;
prev = item2;
}
return prev;
}, {})
if(temp) {
return {...item, ...temp}
}
});
console.log(res);
You can do something like this to merge two arrays.
const arr1 = [
{
name: 'Rohan',
surname: 'Mehra',
age: '15',
date: "2021-01-19",
location: 'Goa'
},
{
name: 'Aman',
surname: 'Kohli',
age: '14',
date: "2021-01-19",
location: 'Kolkata'
},
{
name: 'Sam',
surname: 'Sharma',
age: '16',
date: "2021-01-21",
location: 'Mumbai'
}
]
const arr2 = [
{
rollNo: 1,
marks: 100,
name: 'Rohan',
date: "2021-01-19",
},
{
rollNo: 2,
marks: 90,
surname: 'Kolhi',
date: "2021-01-19",
},
{
rollNo: 3,
marks: 70,
date: "2021-01-21",
ExamCenter: {
place: 'Mumbai'
}
}
]
const newArray = [];
arr2.forEach((item) => {
const array1Item = arr1.find(({ date }) => date === item.date);
if (array1Item) {
newArray.push({
...item,
...array1Item,
})
}
})
console.log(newArray);
This may help you
const arr3 = arr1.map((value, index) => {
return Object.assign(value, arr2[index])
})

Categories

Resources