Convert an object into an array of objects - jsonata

i have a simple array of objects like this
{
"a": [1,2],
"b": [3,4]
}
and I want to put it in this form
[
{ "a": 1, "b": 3},
{ "a": 2, "b": 4}
]
I want to find the right approach here.

Seems like this is a transpose operation where a table is given as an object where the keys are the column names and the values is the column data. The output is supposed to be an array of table rows where each row is an object with the column names are its keys.
(
/* define function that iterates over all columns, gets the i-th array index and merges the results */
$getRow := function($x, $i){
$merge($each($x, function($v, $k) {
{$k: $v[$i]}
}))
};
/* this is the first key that is found, "a" in the example */
$firstKey := $.$keys()[0];
/* this is the first column, [1,2] in the example */
$firstArray := $lookup($, $firstKey);
/* loop over the first array (index is $i) and call $getRow($, $i) */
$map($firstArray, function($v, $i){
$getRow($,$i)
} );
)

Related

MongoDB $addToSet equivalent in CockroachDB

As the title suggests, is there an operator similar to MongoDB's $addToSet in CockroachDB? I want to append a value to an array if it's not present.
I browsed the docs but didn't find an $addToSet operator.
The array_append function should work for this case, see this doc: https://www.cockroachlabs.com/docs/stable/array.html#using-the-array_append-function
You'll need two functions to do this with arrays. Either of these should work:
array_append(array_remove(myArray, newElement), newElement)
IF(array_position(myArray,newElement) IS NULL, array_append(myArray,newElement), myArray)
If what you're representing should never contain duplicates, you might be better off using a JSON object type than an array type, since their keys are automatically unique. Here's an example:
create table unique_groups(id int primary key, vals jsonb default '{}');
insert into unique_groups values (1, '{}'), (2, '{"a": true}');
-- Add "b" to each set
update unique_groups set vals = jsonb_set(vals, '{b}', 'true') where true;
select * from unique_groups;
id | vals
-----+-----------------------
1 | {"b": true}
2 | {"a": true, "b": true}
-- Add "a" to each set
update unique_groups set vals = jsonb_set(vals, '{a}', 'true') where true;
select * from unique_groups;
id | vals
-----+-------------------------
1 | {"a": true, "b": true}
2 | {"a": true, "b": true}

How to sort string with numbers in it numerically?

So I am getting some json data and putting it inside of a Mutable List. I have a class with id, listId, and name inside of it. Im trying to sort the output of the list by listId which are just integers and then also the name which has a format of "Item 123". Im doing the following
val sortedList = data.sortedWith(compareBy({ it.listId }, { it.name }))
This sorts the listId correctly but the names is sorted alphabetically so the numbers go 1, 13, 2, 3. How am I able to sort both the categories but make the "name" also be sorted numerically?
I think
val sortedList = data.sortedWith(compareBy(
{ it.listId },
{ it.name.substring(0, it.name.indexOf(' ')) },
{ it.name.substring(it.name.indexOf(' ') + 1).toInt() }
))
will work but it is not computationally efficient because it will call String.indexOf() many times.
If you have a very long list, you should consider making another list whose each item has String and Int names.

JSON is object instead of array, if array_diff returns assoc array on Collection->toArray()

My issue is in my json I am expecting an array, but am getting an object.
Details:
I have an array of numbers:
$numbers = [1];
I select from relationship, the "drawn numbers":
$drawnNumbers = Ball::whereIn('number', $numbers)->where('game_id', $card->game->id)->get()->map(function($ball) {
return $ball->number;
})->toArray();
I do a ->toArray() here. I want to find the numbers in $numbers that do not occur in $drawnNumbers. I do so like this:
$numbersNotYetDrawn = array_diff($numbers, $drawnNumbers);
My method then return $numbersNotYetDrawn (my headers accept is application/json).
So now the issue. When $drawnNumbers is an empty array, then the printed json is a regular array like this:
[
1
]
However if the relationship returns $drawnNumbers to be an array with numbers, then json is printed as an object:
{
"0" => 1
}
Does anyone know why this is? Anyway to ensure that json is array?
Edit:
Here is my actual data:
$drawnNumbers = Ball::whereIn('number', $numbers)->where('game_id', $card->game->id)->get()->map(function($ball) {
return $ball->number;
})->toArray();
$undrawnNumbers = array_diff($numbers, $drawnNumbers);
// $undrawnNumbers = array_values(array_diff($numbers, $drawnNumbers)); // temp fix
Replace
$numbersNotYetDrawn = array_diff($numbers, $drawnNumbers);
with
$numbersNotYetDrawn = array_values(array_diff($numbers, $drawnNumbers));
to make sure element keys are reset and array is treated as a simple list and serialized to a JSON list - instead of being treated as an associative array and serialized to a JSON object.
I recently had this same problem and wondered the same thing.
I solved it by adding "array_values", but I was wondering how to reproduce it.
I found it that it is reproduced when array_diff removes an element from the array that isn't the last element. So:
>>> $x
=> [
1,
2,
3,
4,
5,
]
>>> array_diff($x, [5]);
=> [
1,
2,
3,
4,
]
>>> array_diff($x, [1]);
=> [
1 => 2,
2 => 3,
3 => 4,
4 => 5,
]

swift2: get array of keys from dictionary sorted by values

I am trying to get an array o keys from a dictionary where the array is sorted by values. For example:
//dictionary contains [alpha:C],[beta:A],[gamma:B]
My array should return:
//[beta, gamma, alpha]
I tried:
let keys = Array(myDictionary.keys).sort({ (a,b) -> Bool in
a.compare(b) == .OrderedAscending
})
but this returns the order by keys:
//[alpha, beta, gamma]
Given your dictionary
let dict = ["alpha":"C","beta":"A","gamma":"B"]
You can sort the keys by value with this code
let keysSortedByValue = dict.sort { $0.1 < $1.1 }.map { $0.0 }
// ["beta", "gamma", "alpha"]
Update
This screenshot to answer to your comment below

Ruby: Hash w/ Arrays, Returning Associated Key If Value Is In Array

New to Ruby and have run out of ideas. I have an array of books that I would like to 1) Shelve 2) Find which shelf it is on 3) Remove it from the associated shelf if found. For brevity I have an array of 6 books. Each shelf contains 5 books.
library_catalog = [ "Book1", "Book2", "Book3", "Book4", "Book5", "Book6" ]
shelves = Hash.new(0)
catalog_slice = library_catalog.each_slice(5).to_a
count = 1
catalog_slice.each do | x |
shelves.merge!(count=>x)
count+=1
end
From this I know have a Hash w/ arrays as such
{1=>["Book1", "Book2", "Book3", "Book4", "Book5"], 2=>["Book6"]}
This is where I'm having trouble traversing the hash to find a match inside the array and return the key(shelf). If I have title = "Book1" and I am trying to match and return 1, how would I go about this?
I think this should work.
shelves.select { |k,v| v.include?("Book1")}.keys.first
selected the hashes that have a value equal to the title you are looking for (in this case "Book1")
get the keys for these hashes as an array
get the first entry in the array.
to remove the Book from the shelf try this:
key = shelves.select { |k,v| v.include?("Book1")}.keys.first
shelves[key].reject! { |b| b == "Book1" }
get a reference to the array and then reject the entry you want to remove

Resources