push value in map of arrays at a specific postition [duplicate] - javascript

This question already has answers here:
How can I create a two dimensional array in JavaScript?
(56 answers)
Closed 5 years ago.
I am creating a map of array using this:
var m = new Map(Array(40).fill(new Array()).entries());
Now, I want to push values in those array. But when I do this:
m.get(1).push(10)
The value 10 gets pushed into all the arrays instead of the one at 1st position.

You could take another pattern to build independent arrays.
var m = new Map(Array.from({ length: 40 }, _=> []).entries());
m.get(1).push(10);
console.log([...m]);

fill gets single array an uses it to fill all rows of the given array, it doesn't create a new array for each row. This means that your single array reference is shared between all rows. Because array is a reference type, you use the single reference to manipulate it, so the actual object is changed. You can check this by comparing the references of each row.
const arr = new Array(2).fill(new Array());
console.log(arr[0] === arr[1]);
For creating separate arrays, you can see #Nina's answer above

Related

how to push object into an nested array within a loop? [duplicate]

This question already has answers here:
Push is overwriting previous data in array
(2 answers)
Closed 2 years ago.
I am using an angularjs foreach and want to find data objects to load into another objects array.
When doing this, it seems like I am adding the variable and all the added objects change to the last variable values.
var p = {};
angular.forEach(d, function(personnel, index){
if(wo.doc.job === personnel.job){
p["EmployeeID"] = personnel.EmployeeID;
p["Number"] = personnel.Number;
wo.doc.personnel.push(p);
console.log(personnel);
}
});
If this finds to 2 employees for a job, they are added and as i watch the wo.doc object after the second object is added the 2 added objects are the same as the last object.
Make a new object in the loop.
angular.forEach(d, function(personnel, index){
if(wo.doc.WorkOrderDetailID === personnel.PrimeWorkOrderNum){
var p = {EmployeeID: personnel.EmployeeID, Number: personnel.Number};
wo.doc.personnel.push(p);
}
});

Splitting an array into more than one array [duplicate]

This question already has answers here:
Split array into chunks
(73 answers)
Closed 7 years ago.
I have a dynamic created array:
var myArray = ['content_1','content_2','content_3','content_4'];
Other times my array could have more items in as such:
var myArray = ['content_4','content_4','content_new','content_new','content_new','content_new','content_new'];
My if statement looks like:
if (myArray.length > 8) { //then do something }
If myArray has more then 8 items in the array, create a new one, each array can only hold 8 items though. So my first array could have 40 items in, 20 items in, or more... I never know, how could I split these into dynamic arrays, is there a way I can do this?
After the 8th item in myArray push those 8 into a new array, then the next 8 (if applicable) and so forth
You'd either have to store your arrays in another array or create a new variable for each array. Personally I'd use an array to store all the arrays so you can still look through all of them when you need to.
var arrays = [['item', 'item'], ['item','item']];
if(arrays[arrays.length].length === 8) {
arrays.push(['new array']);
}
Obviously this won't work for every scenario but it would have to be something similar.

Delete random objects from array [duplicate]

This question already has answers here:
Picking 2 random elements from array
(10 answers)
Closed 7 years ago.
I have an array such as:
array=['a','b','c','d','e','f'];
I want to delete a random 2 elements. How can I do this?
To get two unique items from the array, and if you don't mind mutating the original array, you can use splice() to remove the selected item from the array so it won't be picked when you run it a second time:
var firstRandomChoice = array.splice(Math.floor(Math.random()*array.length), 1);
var secondRandomChoice = array.splice(Math.floor(Math.random()*array.length), 1);
If you use a utility library such as lodash, you may already have a function available to do this for you. For example, lodash provides sample(). So if you were using lodash, you could just do something like this to get an array of two random items:
var results = _.sample(array, 2);

Counting Object Length based on key value [duplicate]

This question already has answers here:
How can I only keep items of an array that match a certain condition?
(3 answers)
Closed 8 years ago.
I have a JS object/ associative array with some values:
var array =[
{val:1,ref:10,rule:100},
{val:1,ref:12,rule:120},
{val:2,ref:13,rule:165},
];
And I want to perform a .length, but want to be able to slice based on one of the keys (for instance val == 1). I want the length of values with val 1 rather than the length of the entire object. I have looked through the references material and could not find a satisfactory answer and I am unsure if this is feasible.
array.val==1.length = 2
Something like that...
You want to .filter the array for elements that match some predicate:
var filteredArray = array.filter(function(element) { return element.val == 1 })
filteredArray.length // = 2
filter applies the callback function to each element in the array, and the new filtered array contains all elements from original array for which the filter callback function returned true. Here, the function returns true for all elements with a val property of 1.
You need to use a .filter():
array.filter(function(v){return v.val==1}).length

jQuery (or JS) How to make a Randomized New Array From an existing one [duplicate]

This question already has answers here:
Sampling a random subset from an array
(15 answers)
Closed 8 years ago.
Say I had
var imgs = ["pItem1","pItem2","pItem3","pItem4","pItem5"]
How can get a new array from the current one, that randomly picks lets say 3 items from the old array and puts it in a new array.
var newArray =["pItem1," "pItem4," "pItem2"];
You're basically looking to take a randomly sampled subset of an array. One approach is to randomly shuffle the array, then take a slice from the beginning of the array. See this implementation of getRandomSubarray() in another answer: https://stackoverflow.com/a/11935263/2943575

Categories

Resources