Javascript Compare 2 array of object based on key and value - javascript

I have 2 arrays of objects below. I want to compare both and check the matched random_code and get the score
based on the matched random code. I have provided the sample result below. Thanks
me.records.data1(array of objects)
[
{
id: 345,
user: 223,
random_code: "50-3910111611011",
created_at: "2019-03-01",
is_verified: false,
…
} 1:{
id: 346,
user:223,
random_code:"50-101966854102",
created_at:"2019-03-01",
is_verified:false,
…
}
]
me.records.data2(array of objects)
[
{
id:161,
questionaire_content:80,
questionaire_content_choice:272,
created_at:"2019-03-01",
random_code:"50-3910111611011",
score:"0",
…
} 1:{
id:162,
questionaire_content:79,
questionaire_content_choice:270,
created_at:"2019-03-01",
random_code:"50-101966854102",
score:"1",
…
}
]
result should be like this based on the data above.
]{
id:345,
user:223,
random_code:"50-3910111611011",
created_at:"2019-03-01",
score:0,
is_verified:false,
…
}{
id:346,
user:223,
random_code:"50-101966854102",
created_at:"2019-03-01",
score:1,
is_verified:false,
…
}
]

What you need to do is:
Iterate over the source array.
For each item in the source array, get the “random_code” key for the object, and store the value in a temporary variable.
From the scores array, find an object whose “random_code” matches the one stored in the temporary variable, if found, return the “score” key’s value.
const source = [
{
id: 345,
user: 223,
random_code: "50-3910111611011",
created_at: "2019-03-01",
is_verified: false,
}, {
id: 346,
user:223,
random_code:"50-101966854102",
created_at:"2019-03-01",
is_verified:false,
}
];
const scores = [
{
id:161,
questionaire_content:80,
questionaire_content_choice:272,
created_at:"2019-03-01",
random_code:"50-3910111611011",
score:"0",
}, {
id:162,
questionaire_content:79,
questionaire_content_choice:270,
created_at:"2019-03-01",
random_code:"50-101966854102",
score:"1",
}
];
// function to get the value of score key from scores array for matching random code.
const getScoreForRandomCode = (randomCode) => {
for (let index = 0; index < scores.length; index++) {
const tempScore = scores[index];
if (tempScore.random_code === randomCode) {
return tempScore.score;
}
}
}
const result = source.map ((item) => {
const randomCode = item.random_code;
const score = getScoreForRandomCode (randomCode);
return {
...item,
score: score || 'NA'
};
});
console.log (result);

Use forEach to loop through the me.records.data1, and match the random_code within me.records.data2. When the random_code matched, will assign the data2.score to me.records.data1.
me.records.data1.forEach(function(obj){
var bscore = "";
data2 = me.records.data2.find(function(i) { if(i.random_code === obj.random_code) return i.score; });
if(bscore!="") obj.score = data2.score;
});

Related

adding another key and value to an object inside an array with JS

So I currently have a bunch of objects inside an array like below. However, I'm now trying to write a function that allows me to add another key|value into the object that was added last.
My current idea is using the arrayname.length - 1 to work out the position of the object within the array.
Would I need to create a temporary array to store the new object and then set (tempArray = oldArray) at the end of the function or would I concatinate them both?
const state = [
{
userId: 1,
},
{
Name: name,
},
{
age: 52,
},
{
title: "et porro tempora",
}]
this is the current code
let objects = [];
const addParent = (ev) =>{
ev.preventDefault();
// getting the length of the objects array
let arrayLength = objects.length;
// if the length of the array is zero - empty or one then set it to default zero
// else if there is objects stored in the array minus 1 to get the array position
if(arrayLength <= 0){
arrayLength = 0;
}else{
arrayLength = objects.length - 1;
}
//make a temporary array to be able to push new parent into an existing object
var tempObjects = []
for (var index=0; index<objects.length; index++){
}
//create a new parent object key : value
let parent = {
key: document.getElementById('key').value,
value: document.getElementById('value').value
}
//push parent object key and value into object
//objects.push(parent);
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('btn1').addEventListener('click', addParent);
});
There are multiple ways to do this.
Try this one
var objects = [{
name: "1"
}];
const addParent = (ev) => {
let parent = {
key: "some value",
value: "some value"
}
objects = Array.isArray(objects) ? objects : [];
let lastObjectIndex = objects.length - 1;
lastObjectIndex = lastObjectIndex > -1 ? lastObjectIndex : 0
objects[lastObjectIndex] = { ...objects[lastObjectIndex],
...parent
}
}
I think You want to add new value to last object of the array
Method 1
const state = [
{
userId: 1,
},
{
Name: name,
},
{
age: 52,
},
{
title: "et porro tempora",
}]
state[state.length - 1].newKey = "value"
console.log(state)
Method 2
const state = [
{
userId: 1,
},
{
Name: name,
},
{
age: 52,
},
{
title: "et porro tempora",
}]
// 1st method
state[state.length - 1] = {
...state[state.length - 1] ,
newKey : "value"
}
console.log(state)
You can probably use something like this:
const a = [
{ "a" : "a" },
{ "b" : "b" }
]
const c = a.map((obj, index) => {
if (index === a.length -1) {
return { ...obj, newProp: "newProp" }
}
return obj;
});
console.log(c)
This will add property on the last object using spread operator, you can look it up if you are new to JS but basically it will retain all the existing property and add the newProp to the object

Remove entire key when matched with matched array values

I am new to react, I have an object and an array, I want to get details of unmatched items from the object when compared with array values. I tried but shows all the data when consol.log. here is my code
var content:[
0:{id:20, name:'Jack Daniel'}
1:{id:21, name:'Sophie McDonald'}
2:{id:22, name:'Jason Thomas'}
3:{id:23, name:'Chris Williams'}
]
var filter:[Sophie McDonald, Chris Williams]
filterValues = content.filter(item=> {
for(var i = 0;i<filter.length;i++) {
if (item.name === filtered[i])
{
return item
}
}
});
console.log(filteredValues)
// returns 0:{id:21, name:'Sophie McDonald'}
// 1:{id:23, name:'Chris Williams'}
But I need unmatched results,
filterValues = content.filter(item=> {
for(var i = 0;i<filter.length;i++) {
if (item.name !== filtered[i])
{
return item
}
}
});
console.log(filteredValues)
// returns 0:{id:20, name:'Jack Daniel'}
// 1:{id:21, name:'Sophie McDonald'}
// 2:{id:22, name:'Jason Thomas'}
// 3:{id:23, name:'Chris Williams'}
Result must be
0:{id:20, name:'Jack Daniel'}
1:{id:22, name:'Jason Thomas'}
Try using filter, checking if the values of the array are present in your object values:
const content = [{
id: 20,
name: 'Jack Daniel'
},
{
id: 21,
name: 'Sophie McDonald'
},
{
id: 22,
name: 'Jason Thomas'
},
{
id: 23,
name: 'Chris Williams'
}
];
const values = ['Sophie McDonald', 'Chris Williams'];
const filteredValues = content.filter(({
name
}) => !values.includes(name));
console.log(filteredValues);
Seems to work with a few edits to the format:
let content = [
{id:20, name:'Jack Daniel'},
{id:21, name:'Sophie McDonald'},
{id:22, name:'Jason Thomas'},
{id:23, name:'Chris Williams'}
]
let filter = ["Sophie McDonald", "Chris Williams"]
let filterValues = content.filter(item=> {
for(var i = 0;i<filter.length;i++) {
if (item.name !== filter[i]){
return item
}
}
});
console.log(filterValues)

How to concatenate object values with same id

I have an array:
let ar = [
{
uid:1,
flat_no: 1
},
{
uid:2,
flat_no: 2
},
{
uid:1,
flat_no:3
}
];
If uid are same then I want to remove duplicate uid and concatenate its flat_no. The output array should be like this:
[
{
uid:1,
flat_no: [1,3]
},
{
uid:2,
flat_no: 2
}
];
You can use a combination of Array.reduce and Array.find.
If you find an existing item in your accumulator array, just update it's flat_no property, otherwise push it to the accumulator array.
let arr = [
{
uid: 1,
flat_no: 1
},
{
uid: 2,
flat_no: 2
},
{
uid: 1,
flat_no: 3
}
]
arr = arr.reduce((arr, item) => {
const existing = arr.find(innerItem => innerItem.uid === item.uid)
if (existing) {
existing.flat_no = Array.isArray(existing.flat_no)
? existing.flat_no
: [existing.flat_no]
existing.flat_no.push(item.flat_no)
} else {
arr.push(item)
}
return arr
}, [])
console.log(arr)
You can iterate over your array and fill an object (used as a hashmap here).
Once done, you extract the values to get your result.
let hashResult = {}
ar.forEach(element => {
if (hashResult[element.uid] == undefined) {
hashResult[element.uid] = { uid: element.uid, flat_no: [] }
}
hashResult[element.uid].flat_no.push(element.flat_no)
})
let result = Object.values(hashResult)
console.log(new Date(), result)
You can do this in a concise way with a single Array.reduce and Object.values to match your desired output:
let data = [ { uid:1, flat_no: 1 }, { uid:2, flat_no: 2 }, { uid:1, flat_no:3 } ];
const result = data.reduce((r, {uid, flat_no}) => {
r[uid] ? r[uid].flat_no = [r[uid].flat_no, flat_no] : r[uid] = {uid, flat_no}
return r
}, {})
console.log(Object.values(result))
1)Reduce the initial array to an object which has uid as the key and the flat_no as the value.
2)Then run a map on the keys to convert it into an array of objects with uid and flat_no.
1) First Step Code
let ar = [{uid:1, flat_no: 1},{uid:2, flat_no: 2},{uid:1, flat_no:3}];
let outputObj = ar.reduce((outputObj,currObj,currIndex) => {
let {uid,flat_no} = currObj
if (outputObj[uid]) {
outputObj[uid].push(flat_no)
}
else {
outputObj[uid] = [flat_no]
}
return outputObj
},{})
2)
let finalOutput = Object.keys(outputObj).map(key =>
({uid:key,flat_no:outputObj[key]}))
console.log(finalOutput)

Get array of all unique object values based on property name

How can I get an array with all the unique values based on a property name?
In my case my object looks like this and I want an array with the unique documentID's.
const file = {
invoice: {
invoiceID: 1,
documentID: 5
},
reminders: [
{
reminderID: 1,
documentID: 1
},
{
reminderID: 2,
documentID: 1
}
]
}
The result should be an array [5, 1] //The unique documentID's are 5 and 1
It doesn't seem like possible to add a property name to the Object.values() function.
You can use Set to get unique documentID.
const file = {
invoice: {
invoiceID: 1,
documentID: 5
},
reminders: [
{
reminderID: 1,
documentID: 1
},
{
reminderID: 2,
documentID: 1
}
],
payments: {
documentID : 5
}
};
var keys = Object.keys(file).map(key=>file[key].map ? file[key].map(i=>i.documentID) : file[key].documentID)
var keysFlattened= [].concat.apply([], keys);
var unique = new Set(keysFlattened);
console.log(Array.from(unique));
I use something like this that does what you want I think
const keepUniqueBy = key => (array, item) => {
if (array.find(i => item[key] === i[key])) {
return array;
} else {
return [ ...array, item ];
}
};
Then you can simply: const unique = reminders.reduce(keepUniqueBy('documentID'))
NB: It's probably low performing, but for small arrays it doesn't matter.

Add scores of array with objects that have the same ID

I have an array of objects:
console.log(quizNight[0].round[--latestRound].t)
-> [ { teamID: 16867, correctAnswers: 1 },
{ teamID: 16867, correctAnswers: 1 },
{ teamID: 16867, correctAnswers: 1 } ]
and I want to have a correctTotalAnswers array to look like this:
[ { teamID: 16867, correctTotalAnswers: 3} ]
What would be the smartest way to go about it? The code which I have now:
let correctAnswersArrayRoung = quizNight[0].round[--latestRound].t;
let totalCorrentAnswersArray = [];
for (let correctAnswer in correctAnswersArrayRoung) {
console.log(correctAnswersArrayRoung[correctAnswer])
for(let element in totalCorrentAnswersArray){
if(element.teamID === correctAnswer.teamID){
element.totalCorrectAnswers = ++element.totalCorrectAnswers
} else {
totalCorrentAnswersArray.push({
teamID: correctAnswer.teamID,
totalCorrectAnswers: 1
})
}
}
}
console.log(totalCorrentAnswersArray)
this returns []
You can use reduce this way (see the inline comments):
// Your initial data
const initialArray = [
{ teamID: 16867, correctAnswers: 1 },
{ teamID: 16867, correctAnswers: 1 },
{ teamID: 16866, correctAnswers: 1 }
]
// Use reduce to loop through the data array, and sum up the correct answers for each teamID
let result = initialArray.reduce((acc, c) => {
// The `acc` is called "accumulator" and it is
// your object passed as the second argument to `reduce`
// We make sure the object holds a value which is
// at least `0` for the current team id (if it exists,
// it will be used, otherwise will be initialized to 0)
acc[c.teamID] = acc[c.teamID] || 0
// Sum up the correctAnswers value
acc[c.teamID] += c.correctAnswers
return acc
}, {}) // <- Start with an empty object
// At this point the result looks like this:
// {
// "16866": 1,
// "16867": 2
// }
// Finally convert the result into an array
result = Object.keys(result).map(c => ({
teamID: c,
correctAnswers: result[c]
}))
console.log(result);

Categories

Resources