I'm trying to assign row object to an array from a check box click event. For this i have created a global array like below.
SelectedGrid: any[] = [];
At the moment of clicking it seems it going into the array, but when i checked the second checkbox 1st item is gone missing from the array.
May I know why that happens?
following is the function i call in check box click event.
public clickConditionRow(row, col, rowSelected) {
if (rowSelected.isChecked) {
this.SelectedGrid.push(rowSelected);
console.dir(this.SelectedGrid);
console.log(this.SelectedGrid.length);
} else {
console.log("Unselected ");
var toDel = this.SelectedGrid.indexOf(rowSelected);
this.SelectedGrid.splice(toDel);
console.dir(this.SelectedGrid);
}
if (!this.rootScope.$$phase) {
this.rootScope.$apply();
}
// for print the values
for (var y = 0; y < this.SelectedGrid.length; y++) {
console.log("Element " + y + " = " + this.SelectedGrid[y]);
console.dir(this.SelectedGrid[y]);
}
}
I cannot reproduce your bug (maybe you are overriding the array somewhere else?) but I see 2 potential problems and want to point them out:
Using indexOf with and object might not work and return -1 (see the code below)
splice(toDel) should be splice(toDel, 1) or it will delete all items staring from index toDel to the end of the array.
const a = { id: 1 }
const b = { id: 2 }
const list = [ a, b ]
// This returns 1
console.log(list.indexOf(b))
// This returns -1
console.log(list.indexOf({ id: 2 }))
Related
.subscribe((dataTotal) => {
console.log(dataTotal)
this.toGetHourData=dataTotal;
const AssociateArray = []
AssociateArray.push({dataTotal : Number})
let associateSum: number = 0;
AssociateArray.forEach(a => associateSum += a.value);
console.log(associateSum);
},
This is my code. I have pushed all of the object into an array. but when i try to sum it up. the console log a NaN.
p.s: this is my first time with stackoverflow
There are a number of issues in your code
1. Incorrect type declaration
You have declared dataTotal : Number For types you need to use number not Number hence dataTotal : number
2. You are adding a type to an array!
Consider the code AssociateArray.push({dataTotal : Number}). {dataTotal : Number} is basically a type so you are pushing an empty type to the array...
3. You can use other means to sum e.g using reduce
With these in mind you can change your code to
.subscribe((dataTotal) => {
this.toGetHourData = dataTotal;
let associateSum: number = dataTotal.reduce((prev, next) => prev + next.value , 0);
console.log(associateSum);
}
.subscribe((dataTotal) => {
console.log(dataTotal)
this.toGetHourData=dataTotal;
var clean = []
var totalnum = 0;
var associateArray = dataTotal
associateArray.forEach(element => {
if (element.strTotalAssociates !== NaN) {
clean.push(element)
console.log(element)
totalnum += element.strTotalAssociates;
console.log(totalnum)
}
});
this is the answer that me and my colleague came up with and its work.
I am using ReactJs Hooks, I have two state array variable one containing list of items from that i am filtering by boolean value and want to add into another state array variable, i tried many ways not working working its only adding last item of the loop with only arr.Push()
arr.concat()
setlstRolePageMapping([...lstRolePageMapping,arr);
arr.push()
const handleAdd = () => {
let arr = [];
for (let data of lstPage) {
if (data.Select) {
objRolePage.Flag = "INSERT" ;
objRolePage.RoleId = 2 ;
objRolePage.PageId = data.PageId;
objRolePage.UpdatedBy = 775 ;
arr.push(objRolePage);
}
}
console.log(JSON.stringify(arr));
}
Following codes are not working
setlstRolePageMapping([...lstRolePageMapping, objRolePage] );
arr.concat(objRolePage);
The issue here is that you're reusing the same object for each loop run (objRolePage). Pushing it to the array does not make a copy of it so you end up pushing the same object which is then modified in the next loop run.
You may fix it by resetting objRolePage on each loop run, for example:
let arr = [];
for (let data of lstPage) {
if (data.Select) {
const objRolePage = {
Flag: 'INSERT',
RoleId: 2,
PageId: data.PageId,
UpdatedBy: 775,
};
arr.push(objRolePage);
}
}
Use ES for second array too (line 12)
1. let arr = [];
2. for ( let data of lstPage) {
3. if (data.Select) {
4. objRolePage.Flag = "INSERT" ;
5. objRolePage.RoleId =2 ;
6. objRolePage.PageId = data.PageId;
7. objRolePage.UpdatedBy = 775 ;
8. arr.push(objRolePage);
9. }
10. }
11. setlstRolePageMapping([...lstRolePageMapping,...arr]); // <=== new line
12. console.log(JSON.stringify(arr));
This might be less difficult than I'm making it out to be, but I'm trying to make a Discord.JS bot command, that will take however many arguments I have. For example: !randomize 1,2,3,4,5,6,7,8,9,10
And the bot would respond with something like: "I have chosen: 4,2,7,3,9!" Any help?
Current attempt: Not exactly sure what I'm doing.
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}`
`bot.on('message', async msg => {
if(msg.content === "!add") {
//message.member.user.tag
var msgArray = msg.content.split(" ");
var args = msgArray.slice(1);
var user = args[1];
//if(!args[1]) return msg.channel.send("Please specify an argument!");
if(nameList.includes(user)) {
msg.reply("You're already on the list.")
} else {
nameList.push(args[1]);
msg.channel.send(`${args[1]} has been added to the list!\n Current List:` + nameList);
}
}
if(msg.content === "!bonus") {
if(nameList.length === 0) {
msg.reply("Either the list is empty, or I'm not in the mood!");
} else {
shuffleArray(nameList);
var chosenOne = nameList.pop();
nameList = [];
msg.reply(chosenOne + ' has been chosen! Good luck!');
}
}
if(msg.content === "!list") {
if(nameList.length === 0) {
msg.channel.send("Either the list is empty, or I'm not in the mood!");
} else {
msg.channel.send('The current list:' + nameList);
}
});```
Here's some simple steps to select 5 random elements from an array...
Construct an array of possible selections. In this example I've used names for the first 10 letters of the alphabet. In your code, it'll be the command arguments or predefined nameList.
Make a new array to hold the elements picked.
At some point before #3, you should check to make sure the pool the user has provided is large enough to make 5 selections (Array.length).
Use a for loop to execute the next code multiple times.
Generate a random number representing the index of a selected element (Math.random(), Math.floor()/double NOT bitwise operator).
Push the selection into the array.
Remove the chosen element from the original pool (Array.splice()).
Return the results.
const pool = ['Albert', 'Bob', 'Charlie', 'David', 'Edward', 'Francis', 'George', 'Horacio', 'Ivan', 'Jim'];
const selected = [];
for (let i = 0; i < 5; i++) {
const num = ~~(Math.random() * pool.length);
selected.push(pool[num]);
pool.splice(num, 1);
}
console.log(`I have chosen: ${selected.join(', ')}`);
Take this example and manipulate it within your code to suit your purpose.
I would like to sort my array to do this I declared 2 temporary array but the both array are already filled even just after the initialization.
Seems like i got a memory problem
let tmpCheckDeals : any[] = [];
let tmpUncheckDeals: any[] = [];
console.log('Init :' , tmpCheckDeals, tmpUncheckDeals);
this.checkedDeals.forEach(element => {
tmpCheckDeals.push(element);
});
for (let i = 0; i < this.deals.list.length; i++) {
let isInside : boolean = false;
const element = this.deals.list[i];
for (let a = 0; a < this.checkedDeals.length; a++) {
const element1 = this.checkedDeals[a];
if(element == element1)
isInside = true;
}
if(isInside == false) {
console.log('Passe');
tmpUncheckDeals.push(element);
}
isInside = false;
}
Result of my console:
console
As you can see my arrays are already filled
Do you have an idea why i get this error pls ?
Thanks
Your code is working as expected. The console displays the value of the array after the entire code has been executed. If you hover over the "i" icon near the array, it would say "Value below was evaluated just now".
For confirmation, you can check by commenting out the remaining code, except the console log.
I have a dynamic object that consists of the number of occurrences from a user selection. The object looks like this:
{ "Excitement": 2, "Competence": 3, "Sophistication": 1 }
This is the function:
rankFactors() {
const headers = this.headers;
var counts = {};
for (var i = 0; i < headers.length; i++) {
var num = headers[i];
counts[num] = counts[num] ? counts[num] + 1 : 1;
}
return counts;
}
How do I sort this object so that it is always in descending order? That way I can print it as a 'Top 3' list.
This is my CodeSandbox: https://codesandbox.io/embed/vue-template-mzi03
To reproduce just make selection of personality traits, with multiple options from a few headers.
I think I'd do it something like this:
rankFactors() {
const headers = this.headers;
const counts = {};
for (const header of headers) {
counts[header] = (counts[header] || 0) + 1;
}
const factors = Object.keys(counts).map(header => {
return {
name: header,
count: counts[header]
}
});
factors.sort((a, b) => b.count - a.count);
return factors;
}
The first stage is very similar to what you had, building up an object of counts. That's an easy data structure to work with for gathering those counts but once that stage is done it's not a great choice for dealing with sorting. For that we're better off with an array.
So next up it converts the object into an array of objects, each of the form {name: 'Excitement', count: 2}. This array is then sorted based on the counts and then returned. You could throw in a .slice(0, 3) if you just want the top 3.