List comprehension based on a dictionary in Javascript - javascript

I use list comprehension often in Python specifically to create a list from a dictionary of key values, in a sorted manner, I define the sorted keys in a list and use comprehension to get a sorted list, I have been looking around but could not find a similar method of doing the following in Javascript other than using a map:
Is there a better way to do this in Javascript?
In Python:
d = {'k2':'v2','k4':'v4','k3':'v3','k6':'v6','k5':'v5'}
list_keys=['k1','k2','k3','k4','k5','k6']
list_wanted_values = [d[c] for c in list_keys]
#list_wanted_values=['v1','v2','v3','v4','v5','v6']
In Javascript:
var js_list_wanted_values = list_keys.map(function(k){
js_list_wanted_values[k] = d[k]
)}

maybe this
var js_list_wanted_values = list_keys.map(k => d[k])

Your map should be more like
var js_list_wanted_values = list_keys.map(function(k){
return d[k]
})
map() creates a new array by returning a new value based on value of each element in array being iterated

Related

JS: Iterate over an array of objects to update object

I am trying to iterate over an array of array objects to de-dupe and sort the data within each. The function onlyUnique returns unique values in an array. The problem is, it doesn't work as intended.
arr_lists = [arr_1, arr_2, arr_3, arr_4, arr_5, ...]
for (var list_obj of arr_lists) {
list_obj = list_obj.join().split(',').filter(onlyUnique);
list_obj.sort();
Logger.log(list_obj);
}
The logger results show true (i.e. they are what I am looking for), but the original array is unchanged, although I think it should have been updated.
I've tried assigning the filtered array to a new array... nope.
I know that I could add a thousand lines of code to achieve the results, but that seems silly.
I suspect it's something obvious.
You can simply achieve it by using Set data structure to remove the duplicates and Array.sort() compare function to sort the elements in an array.
Live Demo :
const arr_lists = [[2,3,5,6], [7,2,5,3,3], [1,5,3], [4,7,4,7,3], [1,2,3]];
arr_lists.forEach((arr, index) => {
arr_lists[index] = [...new Set(arr)].sort((a, b) => a -b);
})
console.log(arr_lists);

Map.setAll instead of multiple map.set calls

With map.set(key, value) you can add (or overwrite) a value for a specific key in the map.
If you have a big list of key-value pairs you need to add them all to the list separately:
[['keyA', 'valueA'],
['keyB', 'valueB'],
['keyC', 'valueC']].forEach(pair => map.set(...pair))
This does not look very performant as it involves a lot function calls.
Is there a faster way to do this?
You could take the array directly for a new Map instance.
var keyValues = [['keyA', 'valueA'], ['keyB', 'valueB'], ['keyC', 'valueC']],
map = new Map(keyValues);
console.log([...map]);

Immutable.js Map values to array

I am using the immutable Map from http://facebook.github.io/immutable-js/docs/#/Map
I need to get an array of the values out to pass to a backend service and I think I am missing something basic, how do I do it ?
I have tried :
mymap.valueSeq().toArray()
But I still get an immutable data structure back ?
For example :
var d = '[{"address":"10.0.35.118","cpus":4}]';
var sr = JSON.parse(d);
var is = Immutable.fromJS(sr);
console.log(sr);
console.log(is.toArray());
console.log(is.valueSeq().toArray());
See this http://jsfiddle.net/3sjq148f/2/
The array that we get back from the immutable data structure seems to still be adorned with the immutable fields for each contained object. Is that to be expected ?
Just use someMap.toIndexedSeq().toArray() for getting an array of only values.
It's because the sr is an Array of Object, so if you use .fromJS to convert it, it becomes List of Map.
The is.valueSeq().toArray();(valueSeq is not necessary here.) converts it to Array of Map, so you need to loop through the array, and convert each Map item to Array.
var d = '[{"address":"10.0.35.118","cpus":4}]';
var sr = JSON.parse(d);
// Array of Object => List of Map
var is = Immutable.fromJS(sr);
console.log(sr);
console.log(is.toArray());
// Now its Array of Map
var list = is.valueSeq().toArray();
console.log(list);
list.forEach(function(item) {
// Convert Map to Array
console.log(item.toArray());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.7.5/immutable.min.js"></script>
Map.values() returns an ES6 Iterable (as do Map.keys() and Map.entries()), and therefore you can convert to an array with Array.from() or the spread operator (as described in this answer).
e.g.:
Array.from(map.values())
or just
[...map.values()]

How to make an array from JSON?

Couldn't think of better title.
Important to note: I'm new to js and I guess its the reason I can't figure it out by myself.
I have a JSON array returned from a database, the JSON array represent a set of points.
Example of the JSON array:
var JSON_array = [{lat:1,lng:2}, {lat:1,lng:3},{lat:2,lng:3}...]
I want to make a different array whose elements will be a function and the variables of the function will be the elements from the JSON array, like so:
var coordinates = [
new google.maps.LatLng(1, 2),
new google.maps.LatLng(1, 3),
new google.maps.LatLng(2, 3),
....
];
I made a function using forEach that counts the elements of the JSON array (for learning and trying to find a way to what I want) but I cant think of a way make the array mentioned above.
You could use Array map method:
var coordinates = JSON_array.map(function(coordinate) {
return new google.maps.LatLng(coordinate.lat, coordinate.lng);
})
This method gives you an new array based on (1) the original array and (2) how you deal with each element. Here's more detailed doc for the method.
you can also use regular for loop
coordinates = [];
for(var i=0;i<JSON_array.length;i++){
coordinates.push(new google.maps.LatLng(JSON_array[i].lat,JSON_array[i].lng));
}
For mapping element from one array to another you can use Array.prototype.map function like
var JSON_array = [{lat:1,lng:2}, {lat:1,lng:3},{lat:2,lng:3}...];
var coordinates = JSON_array.map(function(el){ return new google.maps.LatLng(el.lat, el.lng)});
As Grundy commented you can just do:
coordinates = JSON_array.map(function(x) {
return new google.maps.LatLng(x.lat, x.lng);
});
You might want to get your nomenclature straight though, this has nothing to do with JSON.

JS: name/val pairs to array

I'm using a one-off language similar to javascript in syntax, so an answer in that more common language should suffice.
I have a list of name/val pairs that i built from a big GET string that looks something like
"n1=v1,n2=v2..."
I'm not sure that my initial approach is correct. I used a primitive in this language
tolist(GETstring,"=")
to split the name value pairs into the above list. Perhaps, this is the wrong approach from the gate.
This gives me
data = [["n1","v1"],["n2","v2"],...]
I'm trying to change this into a named array, such as
data["n1"]="v1";
data["n2"]="v2";
...
so that I can access items by name, not by list index (as it is highly volitale)
What is the better approach to getting the data in this format. I've tried a few including evals but nothing seems to work.
You'll have to split the string up then iterate through it.
var obj = {};
var originalString = "n1=v1,n2=v2";
var splitOriginalString = originalString.split(",");
for (var i = 0; i < splitOriginalString.length; i++) {
var tmpObj = splitOriginalString[i].split("=");
obj[tmpObj[0]] = tmpObj[1];
}
There is no option to do it. You've got two ways to do workaround.
Create two arrays, one for keys and one for values.
var indexes = ["test", "test2"];
var values = ["val", "val2"];
var value = values[indexes.indexOf("test2")]; // will get "val2"
Create nested array with key 0 for your string key and with 1 for its value.

Categories