splitting array of items based on variable value [duplicate] - javascript

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)

Related

position array elements in ascending order (numbers are found as substrings inside the array elements) [duplicate]

This question already has answers here:
Natural sort of alphanumerical strings in JavaScript
(6 answers)
Javascript sort on on part of string
(4 answers)
Closed 7 months ago.
I have an array, I want to position every array element in ascending order but the numbers are found as substrings of the array elements. I sketched the code below to give you an idea of what I am trying to achieve(it works but its ugly). What is the best way to position every element inside an array in ascending order when the numbers are found as substrings inside the array elements. Thanks in advance.
Take a look at my code to better understand my question!
//this works but is uglyyyyy
const myArray = ['test4.js', 'test3.js', 'test1.js', 'test2.js']
let tempArr = []
for (var i = 0; i < myArray.length; i++) {
tempArr.push(myArray[i].replace('test', '').replace('.js', ''))
}
const sortedTempArr = tempArr.sort()
let sortedArray = []
for (var i = 0; i < sortedTempArr.length; i++) {
for (var j = 0; j < myArray.length; j++) {
if (myArray[j].includes(sortedTempArr[i])) {
sortedArray.push(myArray[j])
}
}
}
console.log(sortedArray)
Yes that was ugly ;)
Sort takes a function
For descending, switch a and b
I am assuming only ONE number in the string. The regex will produce a wrong result if you have test2version1.js for example
//this works and is pretty
const myArray = ['test4.js', 'test3.js', 'test11.js', 'test1.js', 'test.js', 'test2.js'];
const re = /\D+/g; // anything not a number
const sortedArray = myArray
.slice(0) // shallow copy
.sort((a, b) => a.replace(re, "") - b.replace(re, ""));
console.log(sortedArray);
.sort() the .match(/\d+/)[0] number of each string (coerced into a number). The bracket notation ([0]) ensures that only the first match is used and everything else is ignored.
const array = ['test4.js','test11.js', 'test3.js', 'test1.js', 'test2.js'];
let result = array.sort((a, b) => +a.match(/\d+/)[0] - b.match(/\d+/)[0]);
console.log(result);

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

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('')));

javascript arrays relating/corresponding to each other

I have two arrays, one with strings of large numbers and the other with the sums of the large numbers added together, is there any way where I can have the two arrays correspond with each other? Like to make location [2] in the first array correspond with the same location in the second array. More specifically, I originally establish the array of large numbers, and I've written a function that creates the second array giving me the sums of each numeral in the large numbers (ex. 123456789 in the first array would be 45 in the second array), but I need to be able to link the two arrays because the first array needs to work with any number of strings of numbers. (sorry if this is confusing; I'm just a little out of my depth on this.)
Here is the code I'm working on:
var theArray = ["585-777-7279", "922-901-8934", "112-211-4857", "994-934-9989"];
var plsWork = function() {
var theArrayTwo = theArray.join().replace(/-/g, "");
var theArrayThree = theArrayTwo.split(",").map(Number);
var phoneSum = theArrayThree.map(function (a) {
return Array.prototype.slice.call(a.toString()).map(Number).reduce(function(b,c) {
return b + c;
});
})
phoneSum.sort().reverse();
console.log(phoneSum);
};
Basically, I just want to know if there's a way that I can get the two arrays (the original and the one created in the function) to correspond. Ideally, I would like to be able to have it where I can show that the smallest sum corresponds with the number from the first array.
If you already have the two arrays, the best way to relate one to another would be to create an array of objects as suggested by #webdeb.
If instead you have the array of large numbers and then all you want is to create a second array that in each index contains the sum of all the digits of the number in the first array, than I would use the following code:
var large_numbers = [1234, 2345, 3456];
function sumDigits(number) {
var digitsArray = [],
string = number.toString(); // convert number to string
for (let i = 0; i < string.length; i++) {
// push the numbers to a temporary array so that
// I can sum them one by one later
digitsArray.push(parseInt(string[i], 10));
}
// return the sum of all the elements of the digitsArray
return tempArray.reduce(function(prev, curr) {
return prev + curr;
})
}
var sumsArray = large_numbers.map(sumDigits); // -> [10, 14, 18]
The sumsArray contains in the sum of all the digits of the number in the large numbers array in the same index.

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

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);

Categories