How can I iterate through a keyed array in JavaScript? [duplicate] - javascript

This question already has answers here:
Getting a list of associative array keys
(6 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
I need to group the rows out of a table that has a matching order number, and then iterate over the groupings.
I have this code working which is creating the perfect array, data-wise:
var multItems = [];
// Combine items under orders,
$('tr.order').each(function(){
var orderNum = $(this).find('.ordernumber').val();
if ( ($('tr.order .ordernumber[value="' + orderNum + '"]').length > 1 ) && !(orderNum in multItems) ){
$('tr.order .ordernumber[value="' + orderNum + '"]').each(function(){
if (!(orderNum in multItems)){
multItems[orderNum] = [];
}
multItems[orderNum].push(this);
});
}
});
// Create new tr with order totals (of each item)
for (var i = multItems.length - 1; i >= 0; i--) {
// Code
};
But it creates an array with a length of 0, apparently, where multItems = [], but multItems[orderNumber] is defined... just with no way to access it if I don't know the order numbers.
I could make an array of the order numbers separately, but that feels like it must be the long way round. If I just create a numbered array, how do I know which number to pop the items from the orders into?

With your current code you have
var orderNum = $(this).find('.ordernumber').val();
where val() returns a string and not a number. So when you are doing multItems[orderNum] it is a string.
For the current code to work, you want to use a for in loop.
for (var prop in multItems) {
if( multItems.hasOwnProperty( prop ) ) {
console.log(multItems[prop]);
}
}
FYI: Order is not guaranteed. Also you should be using an object {} and not an array here.
Now the other thing you can do is to use parseInt to change the string into a number and than magically your for loop would start working. [This is assuming that ordernumber is a numeric value]
var orderNum = parseInt($(this).find('.ordernumber').val(), 10);

Related

splitting array of items based on variable value [duplicate]

This question already has answers here:
Split array into chunks
(73 answers)
Closed 1 year ago.
I have the js code below:
let splits = 23;
let outer_bound_value = 0;
let data = //this is an array of a large number of predefined objects (10,200+)
for (i = 0; i < data.length; i = i + outer_bound_value) {
outer_bound_value = data.length / splits;
let split_arr = array.slice(i, i + outer_bound_value);
}
The desired outcome of this code is to be able to split the mega array into smaller arrays based on what the value of splits is (if splits is 5, split the large array into 5 sections). I think the approach I have above works but it is dependent on splits being able to be go into the length of the object and it could cause outofbounds errors. Anyone have a more efficient way to do what I am trying to do?
First divide the array by the amount of splits you want.
Normally I would use a new Set() as it is much faster than splitting arrays with slice however I have no idea what type of data you have in your arrays, Sets are unique when it comes to ints.
we use recursion and destructuring to return the sliced array. this will return you multiple arrays into the array length/splits.
const splits = 23;
const data = new Array(10000);
const chunkValue = Math.floor(data.length/splits);
function chunkArray(array, size) {
if(array.length <= size){
return [array]
}
return [array.slice(0,size), ...chunkArray(array.slice(size), size)]
}
const newArrays = chunkArray(data, chunkValue)

JavaScript array contains elements but length returns 0 [duplicate]

This question already has answers here:
Length of a JavaScript associative array
(4 answers)
JavaScript array length issue [duplicate]
(2 answers)
Closed 4 years ago.
I am creating an Array of days between 2 given dates, the keys should be formatted as DD/MM/YYYY and the values should be numbers (prices set for each date)
It seems to work because the Array contains the values I give it (via a date picker) but I can not loop through this Array, probably because it's length returns 0 even though it contains elements
Here is a screenshot of the console log statement
Here is the code that creates the Array
var arrayOfDatesBetween = new Array();
// daysBetween = integer representing the count of days between the chosen dates
for (let i = 0; i < daysBetween; i++) {
// just add one day on each iteration but keep count of the first
let q = i === 0 ? i : 1;
let _date = _dateIn.setDate(_dateIn.getDate()+q);
// lcsgDate() formats the date as I need it: DD/MM/YYYY
let __date = lcsgDate(_date);
// getDatePrice() gets the price for the given date by searching into another Array of date:price
arrayOfDatesBetween[__date] = getDatePrice(__date);
}
// result
console.log(arrayOfDatesBetween);
I confirm that changing arrayOfDatesBetween from Array to Object solved the issue and I can now have non-integers as keys, just as I needed, Thanks for commenting and pointing me to the right direction
let arr = [1,2,3]
arr['someCustomDate'] = 'someCustomData'
console.log(arr) // [1,2,3]
console.log(arr['someCustomDate'])
You code is essentially same as above, you're defining the property of an array instead of pushing them into the array.
To handle in your situation, you have two options:
1: for every element of your array, create an object and push them into your array like below:
var arrayOfDatesBetween = new Array();
// daysBetween = integer representing the count of days between the chosen dates
for (let i = 0; i < daysBetween; i++) {
// just add one day on each iteration but keep count of the first
let q = i === 0 ? i : 1;
let _date = _dateIn.setDate(_dateIn.getDate()+q);
// lcsgDate() formats the date as I need it: DD/MM/YYYY
let __date = lcsgDate(_date);
// getDatePrice() gets the price for the given date by searching into another Array of date:price
//HERE <=======
let newObjectElement = { date: __date, price: getDatePrice(__date)};
//arrayOfDatesBetween[__date] = getDatePrice(__date);
arrayOfDatesBetween.push(newObjectElement);
}
// result
console.log(arrayOfDatesBetween);
2: Remain your code, but using Object.keys to loop over __date.
Highly recommended to pick option 1 because thats the sole reason to use Array instead of pushing element as a key

Loop is adding too many items to the final array [duplicate]

This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 4 years ago.
When i use Array.fill to fill a multidimensional array, i get a weird behaviour when pushing to one of the arrays:
var arr = Array(2).fill([]);
arr[0].push(5);
console.log(arr);
//=> prints [[5], [5]]
fill is essentially doing this:
var content = [];
for (var i = 0; i < 2; i += 1) {
arr[i] = content;
}
So, your array will have a reference to the array you've passed to fill in each property.
It sounds weird, but what your code actually does is create an array ([]) and put a reference for that array in each of the items of the Array(2). So whenever you change that reference - every array that is referenced to that Array is changed.
It's exactly the same as:
var a = [];
var arr = Array(2).fill(a);
a.push(5);
console.log(arr[0][0], arr[1][0]);
a[0] = 2;
console.log(arr[0][0], arr[1][0]);
You can see that the values inside the arr are affected by the change to the a array.

Create an object from a string using javascript [duplicate]

This question already has answers here:
split string in two on given index and return both parts
(10 answers)
Closed 6 years ago.
I have a string that looks like this:
YA...Y..............
I need to create an object out of this. I was going to try to create an array from the string (but can't see how) if there was a way of doing a split on character index.
Then I was going to loop through that array and create an object.
I had a solution a bit like this:
// Creat an array
var array = [];
// Get our string length
var len = profileString.length - 1;
// Loop through our lengths
for (var i = 0; i < length; i++) {
// Get our current character
var char = profileString[i];
// Push our character into our array
array.push(char);
}
// Create our object
var obj = {};
// Loop through our array
array.forEach(function (item, index) {
// Add our item to our object
obj['item' + index] = item;
});
// Return our object
return obj;
I need to know if there is a better way of doing this.
You could use Object.create.
console.log(Object.create([...'YA...Y..............']));
ES5
console.log(Object.create('YA...Y..............'.split('')));

Select from array of objects based on property value in JavaScript [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 8 years ago.
I have JSON objects that have several properties such as an id and name. I store them in a JavaScript array and then based on a dropdownlist I want to retrieve the object from the JavaScript array based on its id.
Suppose an object has id and name, how do I select them from my array variable?
var ObjectsList = data;
var id = $("#DropDownList > option:selected").attr("value");
ObjectsList["id=" + id];
Since you already have jQuery, you could use $.grep:
Finds the elements of an array which satisfy a filter function. The original array is not affected.
So something like this:
var matches = $.grep(ObjectsList, function(e) { return e.id == id });
that will leave you with an array of matching entries from ObjectsList in the array matches. The above assumes that ObjectsList has a structure like this:
[
{ id: ... },
{ id: ... },
...
]
If you know that there is only one match or if you only want the first then you could do it this way:
for(var i = 0, m = null; i < ObjectsList.length; ++i) {
if(ObjectsList[i].id != wanted_id)
continue;
m = a[i];
break;
}
// m is now either null or the one you want
There are a lot of variations on the for loop approach and a lot of people will wag a finger at me because they think continue is a bad word; if you don't like continue then you could do it this way:
for(var i = 0, m = null; i < ObjectsList.length; ++i) {
if(ObjectsList[i].id == wanted_id) {
m = ObjectsList[i];
break;
}
}

Categories