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.
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 answers here:
Simplest code for array intersection in javascript
(40 answers)
Closed 4 years ago.
I can't seem to figure this out.
I have two arrays. One of the arrays contains all the IDs of the other array, plus more.
var arr1 = [1,2,3,4,5]
var arr2 = [3,5]
My first array contains a lot more information which my second array does not (many other keys). I need to find a way to select all the elements of the first array that are present in the second array and return them so that I have just the elements of arr2 but with all the additional data in arr1. How can I do this?
EDIT: I should make it clear that in the first array, I am looking for specific IDs that match the indexes of the second array. So the solutions here are really good but not quite what I'm after. Example:
[ 0: { id: 1, name: "fred" } ...]
I want to match the id with my second array, not the index. Hope this makes sense!
I implemented a set data structure few months back, this is the difference function
function difference (firstarr,secondarr) {
let diffSet = [];
for ( let i = 0; i < secondarr.length ; i++ ) {
let hasValue = secondarr.includes(firstarr[i]);
if ( ! hasValue ) {
diffSet.push(secondarr[i]);
}
}
for ( let i = 0; i < firstarr.length ; i++ ) {
let hasValue = secondarr.includes(firstarr[i]);
if ( ! hasValue ) {
diffSet.push(firstarr[i]);
}
}
return diffSet;
};
console.log(difference([1,2,3,4],[3,4]));
Use filter and includes of Array.protitype.
var arr1 = [1,2,3,4,5]
var arr2 = [3,5,7]
console.log(arr1.filter(x=>!arr2.includes(x)));
arr2.forEach(function(x){
if(!arr1.includes(x)){
arr1.push(x);
}
})
console.log(arr1);
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('')));
This question already has answers here:
Convert JavaScript array of 2 element arrays into object key value pairs
(5 answers)
Closed 7 years ago.
I have an array that looks something like this: [["key1", "value1"], ["key2", "value2"]]. I want a dictionary that looks like this: {"key1": "value1", "key2": "value2"}. In Python, I could just pass the array to the dict initializer. Is there some equivalent way of doing this in Javascript, or am I stuck initializing an empty dictionary and adding the key/value pairs to the dictionary one at a time?
It's actually really easy with Array#reduce:
var obj = yourArray.reduce(function(obj, entry) {
obj[entry[0]] = entry[1];
return obj;
}, {});
Array#reduce loops through the entries in the array, passing them repeatedly into a function along with an "accumulator" you initialize with a second argument.
Or perhaps Array#forEach would be clearer and more concise in this case:
var obj = {};
yourArray.forEach(function(entry) {
obj[entry[0]] = entry[1];
});
Or there's the simple for loop:
var obj = {};
var index, entry;
for (index = 0; index < yourArray.length; ++index) {
entry = yourArray[index];
obj[entry[0]] = entry[1];
}
Assuming you have a pairs variable, you can use a map() function workaround (not very elegant, as map is supposed to be used in other scope) :
var convertedDict = {};
pairs.map(function(pair) {
convertedDict[pair[0]] = pair[1];
});
This question already has answers here:
Parse JSON in JavaScript? [duplicate]
(16 answers)
Closed 8 years ago.
I want to know what is the fastest function that can be used to convert a json object into a java script array here an example
var j = '[{"var1":"val1", "var2":"val2"}]';
var arr ===> [var1] = "val1"
The bottom line is to avoid for loops as much as possible
Most modern browsers will support the native JSON.parse function.
var arr = JSON.parse('[{"var1":"val1", "var2":"val2"}]');
console.log(arr);
//Just to be clear for OP
console.log(Array.isArray(arr)); //true
I want the output to be Arr[var1] = "val1"] not [Object]
That means you want to object at index 0 in the array.
var obj = JSON.parse('[{"var1":"val1", "var2":"val2"}]')[0];
console.log(obj['var1']); //val1
If you only want the values:
var values = JSON.parse('[{"var1":"val1", "var2":"val2"}]').reduce(function (values, obj) {
for (var k in obj) values.push(obj[k]);
return values;
}, []);
console.log(values); //["val1", "val2"]
If I understand you correctly, you can use JSON.parse.
var json = '[{"var1": "val1", "var2": "val2"}]';
var arr = JSON.parse(json);
I usually use jQuery, though that might no longer be preferred.
var j = '[{"var1":"val1", "var2":"val2"}]';
var arr = jQuery.parseJSON( j );
This should work well in some older browsers if you need that kind of thing of course.