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('')));
Related
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)
This question already has an answer here:
JS : Convert Array of Strings to Array of Objects
(1 answer)
Closed 2 years ago.
My array is something like this:
languages: ["Afrikaans","Albanian","Arabic","Azerbaijani", "Bengali"...]
I want to convert it so that it looks like:
languages: [{id:0,"Afrikaans"},{id:1,"Albanian"},{id:2,"Arabic"},{id:3,"Azerbaijani"}, {id:4,"Bengali"},...]
Build an object in each iteration step and then return this obj to build the result array.
I have added a key for your languages because otherwise it isn't valid syntax.
let languages = ["Afrikaans","Albanian","Arabic","Azerbaijani", "Bengali"]
let res = languages.map((x, ind) => {
let obj = {
"id": ind,
"lang": x
}
return obj;
})
console.log(res);
A simple for loop does the trick here, and your final result is an array filled with incorrectly formatted objects so I took the liberty of adding the language property as you can see.
Let listOfLanguagesArray be your first array and finalArray be your result
var listOfLanguagesArray = ["Afrikaans","Albanian","Arabic","Azerbaijani", "Bengali"...];
var finalArray = [];
for (var j = 0; j < listOfLanguagesArray.length; j++) {
finalArray.push({
id: j,
language: listOfLanguagesArray[j]
});
}
It does seem that, however, what you're asking for is tedious and unnecessary work because you can traverse an array with more efficient methods than traversing an array of objects for the same information in the same order.
This question already has answers here:
How to create an array containing 1...N
(77 answers)
Fastest way to fill an array with multiple value in JS. Can I pass a some pattern or function to method fill insted of a single value in JS? [duplicate]
(1 answer)
Closed 4 years ago.
I want to create a function that takes input from user and returns an array with all the numbers from 1 to the passed number as an argument. Example: createArray(10) should return [1,2,3,4,5,6,7,8,9,10]. I came up with this solution:
function createArray(input) {
var value = 0;
var array = [];
for (i=0;i<input;i++) {
value++;
array.push(value)
console.log(array)
}
}
createArray(12);
What is the correct and better way of doing it?
I would prefer to use Array.from:
const createArray = length => Array.from(
{ length },
// Mapper function: i is the current index in the length being iterated over:
(_, i) => i + 1
)
console.log(JSON.stringify(createArray(10)));
console.log(JSON.stringify(createArray(5)));
There is no need for the extra variable just do this:
function createArray(input) {
var array = [];
for (i = 0; i <= input; i++) {
array.push(i);
}
return array;
}
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);
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;
}
}