This question already has answers here:
Javascript array non undefined element count
(2 answers)
Closed 2 years ago.
Consider the following typescript:
const myArray: Array<string> = new Array();
myArray[5] = 'hello';
myArray[7] = 'world';
const len = myArray.length;
let totalLen = 0;
myArray.forEach( arr => totalLen++);
console.log('Total elements in the array: ' + len.toString(10));
console.log('Total defined elements in the array: ' + totalLen.toString(10));
Output:
Total elements in the array: 8
Total defined elements in the array: 2
I need to insert data into an array at arbitrary indexes, which creates undefined array elements. I then need to check the total number of defined elements in the array. .length includes the undefined elements, but .forEach only iterates over defined elements.
It seems like there should be a better way to do this, but I just don't know the right methods.
You can filter the array, and then find the length, like so:
myArray.filter(i => i !== undefined).length
You can use for example following myArray.filter(v => v !== undefined).length. There will be sure more solutions for this.
const arrLng = myArray.filter(item=>item !== undefined).length
console.log('Total elements in the array: ' + myArray.length );
console.log('Total defined elements in the array: ' + arrLng);
Related
This question already has answers here:
How to sum elements at the same index in array of arrays into a single array?
(7 answers)
Closed 3 years ago.
I am working with a multi-dimensional array.
the following is my array:
let arr = [[1,2,3],[1,2,3],[1,2,3]];
the length of the inner arrays will always be the same.
I want create a function to add all the arrays elements together with their respective elements and create a new array with the result.
so my desired output is
result =[3,6,9];
You can use nested for loop for that.
let arr = [[1,2,3],[1,2,3],[1,2,3]];
let res = Array(arr[0].length).fill(0);
for(let i = 0;i<arr[0].length;i++){
for(let j = 0;j<arr.length;j++){
res[i] += arr[j][i]
}
}
console.log(res)
This question already has an answer here:
jQuery sort array value in sequence
(1 answer)
Closed 3 years ago.
Suppose I have an array like this:
let array = ["eid_x", "eid_x", "cid_x", "cid_x"]
how would I sort it so it's like this?
let array = ["cid_x", "eid_x", "cid_x", "eid_x"]
The original array is in a random order, example: eid, cid, cid, eid.
Does anyone know how this can be sorted like in the second array?
Split the items into two arrays then grab an item off of one alternating between the two arrays within your loop (or an Array#map in this case).
let array = ["eid_x", "eid_x", "cid_x", "cid_x"]
let eid = array.filter(i => i == 'eid_x')
let cid = array.filter(i => i == 'cid_x')
let result = new Array(array.length).fill(null)
.map((i, idx) => idx % 2 == 0 ? cid.shift() : eid.shift())
console.log(result)
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.
This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Modifying a copy of a JavaScript object is causing the original object to change
(13 answers)
Closed 25 days ago.
In the code below you see that it recognises arrayi as array - i.
Is this system built into js? I was experementing and it didn't function when I wrote array(i) instead of arrayi. The question then extends beyond all to ask if you could do iarray, ariray, arrayii or array(i*i) (just want to figure out the syntax of how this works).
var array = []
var arrayAmount = prompt("Select number of array")
for (var i = 0; i < arrayAmount; i++) {
var arrayi = array
arrayi.push([prompt("Select name for array " + (i + 1)), ["sub-element 1", "sub-elemet 2"], ])
console.log(arrayi)
}
console.log(array1)
Edit: I checked if the code would work if the for loop declares its own arrays instead of copying another array. Turns out it did not work and declared arrayi as arrayi instead of array1 or array2
You're confusing several JS concepts. I'll make some assumptions to explain some things, but feel free to correct me and I'll adjust my answer.
I believe you meant to assign a value at a particular index in the array, but what you ended up doing is creating a variable arrayi that is a reference to array:
var array = [];
array[1] = "foo";
console.log(array); // [undefined, "foo"]
What you did instead was create a reference, which means two different variable names will evaluate to the same object/array:
var array = [];
var reference_to_array = array;
reference_to_array.push("foo");
console.log(array); // ["foo"]
console.log(reference_to_array); // ["foo"]
Your original question includes: "and it didn't function when I wrote array(i) instead of arrayi".
To which the answer is: array(i) should be changed to array[i] when working with arrays.
Instead of fixing your original issue, you ended up creating new variables.
To fix your original code:
var array = [];
// Added parsing to an integer
var arrayAmount = parseInt(prompt("How many items do you want to add to the array?"));
for (var i = 0; i < arrayAmount; i++) {
// Method 1: directly access the index
//array[i] = [ prompt("Select name for array " + (i + 1)), ["sub-element 1", "sub-element 2"] ];
// Method 2 (Recommended): push a new element onto the end of the array
array.push([ prompt("Select name for array " + (i + 1)), ["sub-element 1", "sub-element 2"] ]);
// Log this element
console.log(array[i]);
}
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);