Iterate through array of JSON objects in coffeescript - coffeescript

Hi I have the following looking dataset:
[
{ date:"somedatehere", series1:"series1Value", series2:"series2Value" ..., seriesX:"seriesXValue"},
{ date:"anotherDateHere", series1:"anotherseries1Value", series2:"anotherseries2Value"...,seriesX:"anotherseriesXValue"},...
]
I'd like to loop through this in coffeescript and extract arrays such that I would have an array of dates (comprised of somedatehere, anotherDateHere, etc), series1 values, series2 values, seriesX values, etc.
Preferrably all of these arrays would go in order such that dates[0] === somedatehere and series1[0] === series1Value and series2[0] === series2Value and seriesX[1] === anotherseriesXValue etc.
Is there an easy way to go about doing this in coffeescript?

dates = (obj.date for obj in my_array)
series1 = (obj.series for obj in my_array)
in case you have a lot of series and don't want to manually enumerate them:
types = (k for k, v of my_array[0])
result = {}
result[type] = (obj[type] for obj in my_array) for type in types
Will give you
my_array = [{date: 1, x: 2}, {date: 123, x: 2134}]
result = {
date: [ 1, 123 ],
x: [ 2, 2134 ]
}

Related

Find a text and replace it with a value in Matlab

I have some data which look like this:
I would like to pre-process the data in a way that I replace all Mostly false with 1, Mostly true with 2 and Definitely true w/ 3. Is there a find and replace command or what is the best way of doing this?
You can use a map object to do the mapping
m = containers.Map( {'Mostly false', 'Mostly true', 'Definitely true'}, ...
{ 1, 2, 3} );
Then for some example data
data = {'Mostly false', 'Mostly false', 'Mostly true', 'Mostly false', 'Definitely true'};
You can perform the conversion with
data = m.values( data );
% >> data = {1, 1, 2, 1, 3}
This assumes there will always be a match in your map.
Alternatively, you could do the operation manually (for the same example data), this will leave non-matches unaltered, and you could use strcmpi for case-insensitivity:
c = {'Mostly false', 'Mostly true', 'Definitely true'
1, 2, 3};
for ii = 1:size(c,2)
% Make the replacement for each column in 'c'
data( strcmp( data, c{1,ii} ) ) = c(2,ii);
end

convert elements in list to nested lists in list

I have a list which is needed to be converted to nested lists in a list
my_list = [2,5,6,7,8,15,34,56,78]
I need list as
final_list = [[2,5,6],[7,8,15],[34,56,78]]
I wrote code using for loop with length command and range command, I know there is error with range function, but I couldn't figure it out.
my_list = [2,5,6,7,8,15,34,56,78]
max_split = 3
final_list = [[len(my_list) for _ in range(max_split)] for _ in range(max_split)]
print(final_list)
But the output I get is [[9,9,9],[9,9,9],[9,9,9]]
You can try following code
my_list = [2,5,6,7,8,15,34,56,78]
max_split = 3
final_list = [my_list[i:i + max_split ] for i in range(0, len(my_list), max_split )]
print(final_list)
Demo.
If you use the indexes returned by the for loops, you can use them to count through the indexes in your list like this:
my_list = [2,5,6,7,8,15,34,56,78]
max_split = 3
final_list = [[my_list[i+3*j] for i in range(max_split)] for j in range(max_split)]
print(final_list)
Output:
[[2, 5, 6], [7, 8, 15], [34, 56, 78]]

swift 3 alphanumeric sorting re: I, II, III, IV, IX, V,

Curious to know if anyone can offer a solution to sorting roman numerals (string type) I through X. When I sort an array using {$0.compare ($1, options: .numeric) == .orderedAscending}, I get I, II, III, IV, IX, V, VI, VII, VIII X. As you can see, IX follows IV because of the "I."
By the way, the data model is a dictionary [String:[String:[String]]] The Bold indicates where in the dictionary the data to be sorted exists.
Is this what you mean? Perhaps by converting them first
let romanValues = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let arabicValues = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var romanValue = ""
var startingValue = number
for (index, romanChar) in enumerate(romanValues) {
var arabicValue = arabicValues[index]
var div = startingValue / arabicValue
if (div > 0)
{
for j in 0..<div
{
//println("Should add \(romanChar) to string")
romanValue += romanChar
}
startingValue -= arabicValue * div
}
}
return romanValue
I came up with a simple solution. Rather than hassle with the key of the dictionary to populate the rows of a table view in the desired numeric order, I created a simple array- which is ordered. When a row is selected, I can use didSelectRow to identify the indexPath and the related string of the array- for example row 1 = "Article I". I can then pass the selected string value "Article I" as a variable to use in the selection of the identical key [String:[String:[String]]] within the nested dictionary.
PS - the solution posted by Lucas appears to be a partial copy and paste of a function that can be found on GitHub. It appears Lucas inadvertently failed to copy and paste the entire function.

How to find the Intersection of n arrays

I have n arrays or variable length
arr1 = [1,2,3]
arr2 = [1,3,5,8]
....
How can I compute the intersection of those n arrays ?
Consider checking out underscore.js library. It provides function for what you need and a bunch of other usefull functions.
Example from docs:
_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2]
Simple plain JS implementation can be found here. Same idea in CoffeeScript:
intersect_all = (lists) ->
if lists.length is 0
return []
else return lists[0] if lists.length is 1
partialInt = lists[0]
i = 1
while i < lists.length
partialInt = intersection(partialInt, lists[i])
i++
partialInt
The most efficient way is to use hashsets:
function hashset (elements) {
var i, set = {};
if (!Array.isArray(elements)) return elements;
for (i = 0; i < elements.length; i++) {
set[elements[i]] = true;
}
return set;
};
function intersect (a, b) {
var k
, s1 = hashset(a)
, s2 = hashset(b)
, s3 = {}
for (k in s1) {
if (s2[k]) s3[k] = true;
}
return s3;
};
Object.keys(intersect(arr1,arr2));
// ["1", "3"]
You will find CoffeeScript source of this code, benchmarks for it and some additional information in this question.
If you're going to to intersect huge arrays then I strongly recommend you to use this approach.
Either just use something like _.intersection or study the source of that implementation and rewrite it if you like.

Why doesn't this coffee-script print out?

So when the index is 0, I want to print it out:
a = [ 1, 2, 3 ]
for i of a
if i == 0
console.log a[i]
But there is no output.
i == 0 is never true...
i returns the index as a string, if you parse them as an integer, it would work
a = [ 1, 2, 3 ]
for i of a
if parseInt(i) == 0
console.log a[i]
It's because i will only be 1, 2 or 3, as you loop over the items in a, not the index numbers.
This works the way you described above:
a = [ 1, 2, 3 ]
for i in [0..a.length]
if i == 0
console.log a[i]
You shouldn't use of to loop over an array, you should use in. From the fine manual:
Comprehensions can also be used to iterate over the keys and values in an object. Use of to signal comprehension over the properties of an object instead of the values in an array.
yearsOld = max: 10, ida: 9, tim: 11
ages = for child, age of yearsOld
"#{child} is #{age}"
So you're trying to iterate over the properties of an array object, not its indexes.
You should use one of these for your loop:
for e, i in a
if(i == 0)
console.log(a[i])
for e, i in a
console.log(e) if(i == 0)
console.log(e) for e, i in a when i == 0
#...
Or, since you have an array and a numeric index, why not just skip the loop and get right to the point:
console.log(a[0])