Check Duplicate Nested Object Values within Single Array of Objects - javascript

Some how it becomes very complicated for me to achieve this.
// HERE WE WILL ARE CREATING THE ARRAY OF OBJECTS
let getAllAssetsData = [];
$('#productList tr').not(':first').each(function(index,value){
let getPT = $(this).find('.dropdown').val();
let getPm = $(this).find('.pm').val();
let getSn = $(this).find('.sn').val();
getAllAssetsData.push({
'pt' : getPT,
'pm' : getPm,
'sn' : getSn,
});
});
// THIS IS WHAT I AM TRYING
$(getAllAssetsData).each(function(index1,value1){
$(getAllAssetsData).each(function(index2,value2){
// HERE I NEED TO COMPARE ALL ARRAY VALUES TO EACH OTHER AND MAKE DUPLICATE VALIDATION
if((value1.pt === value2.pt) && (value1.pm === value2.pm) && (value1.sn === value2.sn)){
// HERE DUPLICATE ELEMENT FOUND
console.log(value1.pt);
console.log(value2.pt);
console.log(value1.pm);
console.log(value2.pm);
console.log(value1.sn);
console.log(value2.sn);
alert('asd');
}
});
});
On Click on add button it is very easier for me to only add unique set of values, but if user have rights to change values after adding into the list, so how do i check duplication on click of "NEXT" button ?

Related

Copy array by value is not working in foreach in Angular

I am trying to copy array in element of array and manipulate as per my need.
this.question?.labels.forEach((element) => {
element["options"] = [...this.question?.options]; // I've tried json.stringify() as well but not worked
element["options"].forEach(e => {
e.checked = this.question?.userAnswers.find(i => e.key === i.value && element.key === i.key) ? true : false;
});
});
I've used [...this.question?.options] to get new copy of option every time. but it always saved last value of array in each element
https://stackblitz.com/edit/pass-array-by-value?file=src%2Fapp%2Fapp.component.ts
I do see the right options array populated under each label element. Just formatted the json using pre tag in html to get a better view.
Stackblitz - https://stackblitz.com/edit/pass-array-by-value-b1f6aq?file=src/app/app.component.ts

ReactJS: Map and Find

Introduction
I have a search filter in which I enter parameters such as sender and recipient.
In this way for the sender I make a call and get results.
For the recipient I make another call and get other results.
So I will have two arrays:
sent
sent1
what I would like to do is iterate through the first arrival comparing each element with each element of the second array and if a certain condition is exceeded save the element of the first array.
Now my Code is:
let filteredSent = {rows: []}
sent.rows.map( (elem) => { sent1.rows.find( (value) => {
if(value.key[2] === values.recipient.Code && value.key[0] === "RECIPIENT" && elem.key[1] === value.key[1] && elem.key[3] === value.key[3] && elem.value === value.value){
filteredSent.rows.push(elem)
}
})
} )
where values.recipient.Code is an input value that I choose from a list.
My problem is that I make this comparison, but I find myself certain results that shouldn't be there.
Is what I'm doing the map and find a wrong use?
Thank you all for your time.

how to use includes() after shift() of array of objects

1 - I have an interval going that loops through an array of players.
2 - the array is an array of objects.
example of object
{
id : "100",
fname : "tom",
lname : "smith",
position: 15,
team : "Giants"
};
3 - the array has many players so for example
players_list = [ {"id":"2218","avg":"60.9189","min":"1","max":"380","fname":"Patrick","lname":"Mahomes","position":"QB","team":"Chiefs"},{"id":"65","avg":"48.6216","min":"1","max":"194","fname":"Josh","lname":"Allen","position":"QB","team":"Bills"},{"id":"416","avg":"58.3784","min":"1","max":"213","fname":"Drew","lname":"Brees","position":"QB","team":"Saints"},{"id":"591","avg":"69.0270","min":"1","max":"231","fname":"Derek","lname":"Carr","position":"QB","team":"Raiders"},{"id":"840","avg":"61.1081","min":"1","max":"252","fname":"Sam","lname":"Darnold","position":"QB","team":"Jets"}]
4 - during each loop I take the first using players_list.shift();
5 - then I store each selected player in another array of objects of same structure called selected_players_list. which would include each player that has been selected from shift.
6 - the issue is that the above is only 1 of the ways a player can be selected another way is manually by the user which will also be added into selected_players_list.
7 - I want to automatically remove any player that has been manually selected from being picked again by removing the player from the players_list
8 - I have this code.
// loop through the players array
players_list.forEach(function(element) {
// check if the object exists in the other array
if(selected_players_list.includes(element)){
console.log('FOUND');
debugger;
// get the index of that object found
let found = total_result_player_data.findIndex(obj => obj.id === element.id);
if(found !== -1){
console.log('SPLICED -> ' + found);
// remove it from players list array
players_list.splice(found, 1);
console.log(players_list);
// debugger;
}
}
});
9 - after that I want to shift the first player from the array.
object_random_pick = players_list.shift();
10 - but on second loop the includes does not find that player in the selected_players_list array anymore.
11 - it works correctly if I use this instead.
object_random_pick = players_list[0];
12 - however then its using the same pick repeatedly which isn't what I want.
I don't want any player used more then once.
Dont use .splice or .shift inside of loop. You change array before loop finish this work. If you want give remove some element from array you must use .filter
This code just example how you can use .filter
players_list = [ {"id":"2218","avg":"60.9189","min":"1","max":"380","fname":"Patrick","lname":"Mahomes","position":"QB","team":"Chiefs"},{"id":"65","avg":"48.6216","min":"1","max":"194","fname":"Josh","lname":"Allen","position":"QB","team":"Bills"},{"id":"416","avg":"58.3784","min":"1","max":"213","fname":"Drew","lname":"Brees","position":"QB","team":"Saints"},{"id":"591","avg":"69.0270","min":"1","max":"231","fname":"Derek","lname":"Carr","position":"QB","team":"Raiders"},{"id":"840","avg":"61.1081","min":"1","max":"252","fname":"Sam","lname":"Darnold","position":"QB","team":"Jets"}]
// loop through the players array
const chekedPlayers = players_list.filter(function(element) {
// check if the object exists in the other array
if (selected_players_list.includes(element)) {
console.log('FOUND');
//debugger;
// get the index of that object found
let found = total_result_player_data.findIndex(obj => obj.id === element.id);
if (found !== -1) {
console.log('SPLICED -> ' + found);
// remove it from players list array
return false; //
console.log(players_list);
// debugger;
}
return true;
}
});```
You can read doc of `.filter` and use how you need.

How to remove value from array using index (Ant Design specific)?

I am creating a questionnaire type form using ReactJs and Ant Design. It is a follow up question of How to create a questionnaire type form using Ant Design?
Now I am succeeded in adding new questions and their respective answers but not in removing them. Let's suppose I have added three questions and when I am trying to remove any one of them, its always removing the last one. The related code for removing is as follows:
remove = k => {
console.log(k);
const { form } = this.props;
// can use data-binding to get
const keys = form.getFieldValue("keys");
// We need at least one passenger
if (keys.length === 1) {
return;
}
keys.splice(k, 1);
// can use data-binding to set
form.setFieldsValue({
keys: keys
});
console.log(keys);
};
The complete code can be found as a demo on codesandbox.io.
I have done something similar in the past. Got rid of the boilerplate of antd's remove and replaced with this. Every time I add a row I push that row (object) to formRows array then removing like this:
remove = key => {
const newRows = this.state.formRows.filter(r => r.key !== key)
this.setState(
prev => ({
formRows: newRows
})
)
}

Dynamically call function with multiple arguments

I'm trying to find similar items amongs a dynamic amount of arrays, For example I might have 2 or 3 arrays with data in them, and want to find the which items exist between all of them.
At the minute i've got this "working" but really ugly code which won't scale past 3 items. The GDAX, PLNX etc are all bools which I have available to tell me whether this option is selected.
The intersectionBy is a lodash helper function with further information available here https://lodash.com/docs/4.17.4#intersectionBy
let similarItems = [];
similarItems = GDAX && PLNX && BTRX ? _.intersectionBy(data.BTRX, data.PLNX, data.GDAX, 'pair') : similarItems;
similarItems = GDAX && PLNX && !BTRX ? _.intersectionBy(data.PLNX, data.GDAX, 'pair') : similarItems;
similarItems = GDAX && !PLNX && BTRX ? _.intersectionBy(data.BTRX, data.GDAX, 'pair') : similarItems;
similarItems = !GDAX && PLNX && BTRX ? _.intersectionBy(data.BTRX, data.PLNX, 'pair') : similarItems;
This should do the job
const input = ['GDAX', 'PLNX', 'BTRX']; // here you pass the strings that are given
const result = _.intersectionBy.apply(_, input.map(name => data[name]).concat(['pair']));
The input could also somehow automized, e.g. giving the object of true / false values for each name, so
const inputObject = { GDAX: true, PLNX: false, BTRX: true };
const names = ['GDAX', 'PLNX', 'BTRX'].filter(name => inputObject[name]);
const result = _.intersectionBy.apply(_, names.map(name => data[name]).concat(['pair']));
For readability and easy maintainability, I'd go with explicitly building a selection according to your boolean flags:
let selection = [];
if (GDAX) selection.push(data.GDAX);
if (PLNX) selection.push(data.PLNX);
if (BTRX) selection.push(data.BTRX);
const result = _.intersectionBy(...selection, 'pair');

Categories