pluck based on common attribute (rails) - mysql

I have a table Followership, in which every record has attributes user_id and follower_id.
I can do something like this:
Followership.limit(10).pluck('user_id, follower_id)
But this will give me result like this [[1,A][2,B],[3,C],[4,A],[1,B][2,D]]
I want to convert the above array in such a way that all arrays with same user_ids should be merged in following form [user_id, FOLLOWER_ID(S)]
i.e;
[[1,[A,B]][2,[B,D]],[3,C],[4,A]]
Here user_id = 1 has two followers A,B and user_id = 2 has two followers B,D
How to do this?

As pointed out by Sergio, you could use group_by with the array that you get after pluck, for example:
arr = [[1,'A'],[2,'B'],[3,'C'],[4,'A'],[1,'B'],[2,'D']]
a.group_by(&:first).map { |k, v| [k, v.map(&:last)] }
#=> [[1, ["A", "B"]], [2, ["B", "D"]], [3, ["C"]], [4, ["A"]]]

Another approach
a = [[1,'A'],[2,'B'],[3,'C'],[4,'A'],[1,'B'][2,'D']]
h = Hash.new { |h, k| h[k] = [] }
a.inject(h) { |sum, t| sum[t[0]] << t[1]; sum}.to_a

Related

Karate: How to create a json object/map from 2 arrays and merge them?

I am having 2 arrays
array1 = ['a','b']
array2 = [1,2]
I want to merge these 2 arrays and convert them to map like below:
[
{
"firstparam": 'a'
"secondparam": 1
},
{
"firstparam": 'b'
"secondparam": 2
}
]
I am trying this code:
* def map1 = array1
* def map1 = karate.mapWithKey(map1, 'firstparam')
* def map2 = array2
* def map2 = karate.mapWithKey(map2, 'secondparam')
this code is creating map1 & map2. now I want to merge these 2 maps in the above format. how to do it?
basically, i want to send this map to a feature file which is expected 2 parameters.
* def result = karate.call('*.feature', map)
'*.feature' is expecting 2 parameters per call i.e, firstparam & secondparam
Here you go:
* def array1 = ['a', 'b']
* def array2 = [1, 2]
* def array3 = array1.map((x, i) => ({ firstparam: x, secondparam: array2[i] }))
* match array3 == [{ firstparam: 'a', secondparam: 1 }, { firstparam: 'b', secondparam: 2 }]

merging 2 arrays into an array with 2 columns

I want to merge 2 arrays in the following format.
array1 = [ "a" , "b" , "c"]
array2 = [ 1 , 2 , 3]
merged_array = [ {"a",1} , {"b",2} , {"c",3}]
The goal is to use this as values of 2 columns and rewrite this back to google sheet.
is my format correct and if yes how should i merge the arrays as said above ?
EDIT:
i decided to use this
var output = [];
for(var a = 0; a <= array1.length; a++)
output.push([array1[a],array2[a]]);
how would this compare to map function, performancewise ?
array1 = [ "a" , "b" , "c"]
array2 = [ 1 , 2 , 3]
merged_array = []
for index, value in enumerate(array1): merged_array.append({value,array2[index]})
print (merged_array)
-> [{'a', 1}, {'b', 2}, {'c', 3}]
Merging two arrays into and array of arrays
function myFunk() {
let array1 = ["a", "b", "c"];
let array2 = [1, 2, 3];
let a = array1.map((e,i) => {return [e,array2[i]];})
Logger.log(JSON.stringify(a));
}
Execution log
4:17:09 PM Notice Execution started
4:17:08 PM Info [["a",1],["b",2],["c",3]]
Array.map()

how to make lua table key in order

my test code:
local jsonc = require "jsonc"
local x = {
a = 1,
b = 2,
c = 3,
d = 4,
e = 5,
}
for k, v in pairs(x) do
print(k,v)
end
print(jsonc.stringify(x))
output:
a 1
c 3
b 2
e 5
d 4
{"a":1,"c":3,"b":2,"e":5,"d":4}
someone help:
from for pairs output, lua store table by key hash order, how can i change it?
i need output: {"a":1,"b":2,"c":3,"d":4,"e":5}
thanks
Lua tables can't preserve the order of their keys. There are two possible solutions.
You can store the keys in a separate array and iterate through that whenever you need to iterate through the table:
local keys = {'a', 'b', 'c', 'd', 'e'}
Or, instead of a hash table, you can use an array of pairs:
local x = {
{'a', 1},
{'b', 2},
{'c', 3},
{'d', 4},
{'e', 5},
}

Retrive all the value that satisfy the condition of first table

I have two tables users and location. I need to join both tables
what i need is get all the area number of all the users which are present in the user table.
ie user 1 has 3 entries in the second table so i need to join the table in such a way that is,
id1 = 1
area = 2,3
area 2 is repeating so do not include it twice
i tried the join but now getting the correct way to doing it.
What i tried?
$location = User::
join('addresses','users.id1','=','addresses.id1') ->select('users.id1','addresses.area')
->get();
Expected Output
User 1 -> area ->2,3
Here are the two ways to do this.
Firstly you can use Laravel relationship:-
In your model User create relationship:-
function addresses()
{
return $this->hasMany(Address::class, 'id1', 'id1');
}
Now in your User controller you can get User addresses (areas) like this
$users = User::with('addresses')->get();
dd($users->toArray());
This will print something like this
[
{
id1: 1,
name: abaa
pwd: 12345
addresses: [
{
id2: 1,
id1: 1,
area: 2
},
{
id2: 2,
id1: 1,
area: 3
},
{
id2: 3,
id1: 1,
area: 3
}
]
},
{
...
}
]
Second you can use Laravel relationship:-
$builder = new User;
$builder->join('addresses','users.id1','=','addresses.id1')
->selectRaw("users.*, GROUP_CONCAT(DISTINCT addresses.area SEPARATOR ',') as distinct_areas")
->groupBy("users.id1")
->get();
This query will give you result something like this
[
{
id1: 1,
name: abaa,
pwd: 12345,
distinct_areas: 2,3
},
{
...
}
]
I think this will help you.

Get grouped values by multiple ids in ActiveRecord

Sorry for bad English ))
I have an array of ids in my ruby code.
Example:
[[10], [], [10, 1, 3], []]
Can I load User model from MySQL table users in one query by saving grouping?
Example:
[[#<User id=10>], [], [#<User id=10>, #<User id=1>, #<User id=3>], []]
Environment: Ruby 2.5.1 | Rails 5 | MySQL
One of found solution:
I can flat my array of ids and load my model by that array into hash:
hash = User.where(id: array.flatten).index_by(&:id)
Then, during iterating, through array I can load my objects from hash in the right order like that:
array.each do |ids|
users = ids.map { |id| hash[id] }
# do smth
end
This is simple: use flatten method for array:
ids = [[123], [], [123, 1, 3, 4], [70, 80]]
user_ids = ids.flatten.reject(&:blank?).uniq
users = User.where(id: user_ids)
edited:
not optimal (recursive) method for your need:
def map_users_by_id(ids_array:, users:)
result = []
ids_array.each do |array_element|
if (array_element).is_a? Array
result << map_users_by_id(ids_array: array_element, users: users)
else
result << users[array_element]
end
end
return result
end
ids = [[123], [], [123, 1, 3, 4], [70, 80]]
user_ids = ids.flatten.reject(&:blank?).uniq
users = Hash[User.where(id: user_ids).map{|user|[user.id, user]}]
result = map_users_by_id(ids_array: ids, users: users)