Merge two arrays of objects in Ruby - arrays

I have an array of objects with unique IDs:
[{id: 1, score: 33}, {id: 23, score: 50}, {id:512, score: 27}, ...]
I also have an array of User records with matching IDs. The user records have "name" but not "score":
[{id: 1, name: "Jon"}, {id: 23, name: "Tom"}, {id: 512, name: "Joey"}, ...]
How can I create a single array with each id, name, and score?
[{id: 1, name: "Jon", score: 33}, {id: 23, name: "Tom", score: 50}, {id: 512, name: "Joey", score: 27}, ...]
I tried merge, combine, filter, etc but haven't found the Ruby function to accomplish this.

Assuming that in users there is always record with corresponding :id from scores:
scores = [{id: 1, score: 33}, {id: 23, score: 50}, {id:512, score: 27}]
users = [{id: 1, name: "Jon"}, {id: 23, name: "Tom"}, {id: 512, name: "Joey"}]
scores = scores.map { |score| score.merge(users.find { |user| user[:id] == score[:id] }) }
# => [{:id=>1, :score=>33, :name=>"Jon"}, {:id=>23, :score=>50, :name=>"Tom"}, {:id=>512, :score=>27, :name=>"Joey"}]
Hope that puts you in proper direction!

You can use an intermediate Hash.
hsh = Hash[ a1.map {|h| [h[:id], h[:score]]} ]
# => {1=>33, 23=>50, 512=>27}
a2.map {|h| h[:score] = hsh[h[:id]]; h}
# => [{:id=>1, :name=>"Jon", :score=>33}, {:id=>23, :name=>"Tom", :score=>50}, {:id=>512, :name=>"Joey", :score=>27}]

If, as in the example, scores[i][:id] = users[i][:id] for all i, and you are using v1.9+ (where key insertion order is maintained), you could write:
scores.zip(users).each_with_object({}) do |(sh,uh),h|
h.update(sh).update(uh)
end
Would I use this? Would you?

Related

How to filter array object from another array object?

I want to make another array object from an array object, suppose I fetched a huge data from an api but I need only particular elements from that object. Exampl:-
const mainArray = [
{id: 1, name: 'John', age: 10},
{id: 2, name: 'Mark', age: 14},
{id: 3, name: 'Kevin', age: 15},
{id: 4, name: 'Julie', age: 16},
{id: 5, name: 'Liz', age: 10},
{id: 5, name: 'Emma', age: 11},
{id: 6, name: 'Robert', age: 13},
]
So suppose we have a huge list now I only want Kevin, Emma & Mark to display, for that I need an array of them like this:-
const specialKids = [
{id: 2, name: 'Mark', age: 14},
{id: 3, name: 'Kevin', age: 15},
{id: 5, name: 'Emma', age: 11},
]
How can I achieve that ?
To do this you can use the filter method of JS.
Documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter?retiredLocale=de
in your case something like this should be enough:
let specialKids[];
specialKids = mainArray.filter(item => item.name === "Mark" || item.name === "Kevin" || item.name === "Emma")
ArrayList<String> yourintList = new ArrayList<>(Arrays.asList(yourArray));
for (int i = 0; i < yourintList.lenght; i++) {
if (yourintList.contains("Kevin")) {
do something
}

Using Map Object to Render React Components in Order

I receive an array of product objects like such from my backend.
products = [
{id: 1, price: 10, category: "food", name: "apples"},
{id: 2, price: 5, category: "supplies", name: "spoons"},
{id: 3, price: 15, category: "pets", name: "cat treats"},
{id: 4, price: 9, category: "food", name: "oranges"},
// ...
]
I am looking to render all my products as strips based on their category in a specific order of priority (similar to how Netflix aligns their shows). I don't want them displayed in random order, such as the category strip of food being at the top, the next category strip being pets, etc.
I currently decided to create a map object since it keeps order as followed:
let filteredProducts = new Map([
["food", []],
["pets", []],
["supplies", []],
// ...
])
for (let product of products) {
let category = product["category"]
filteredProducts.get(category).push(product)
}
The goal is to then iterate through the map object and return multiple React Component of category strips from top to bottom.
My question is, I can't help but feel that there are more efficient ways to render this as I don't see map objects being utilized commonly. Are there more efficient and frequently used ways to filter and render by priority or is this in the right direction?
I do believe there is more easier way to do this using Array sort function.
Please consider the snippet below.
const products = [
{id: 1, price: 10, category: "food", name: "apples"},
{id: 2, price: 5, category: "supplies", name: "spoons"},
{id: 3, price: 15, category: "pets", name: "cat treats"},
{id: 4, price: 9, category: "food", name: "oranges"},
// ...
]
const priority = [
'food',
'supplies',
'pets'
]
const orderedProducts = products.sort(
(p1, p2) => priority.indexOf(p1.category) - priority.indexOf(p2.category)
);
Let me know if this looks much cleaner & easier approach.

react awesome query builder limitations with mongodb and embedded doc collections

I have 2 collections, Authors and Books and I want to use react-awesome-query-builder to enable the user to query the data however they like, here are my schemas and data
Authors collection
{id: 1, name: 'JK Rowling', gender: 'F'},
{id: 2, name: 'Roald Dahl', gender: 'M'},
{id: 3, name: 'Dr Seuss', gender: 'M'}
Books collection
{id: 1, author_id: 1, title: 'Harry Potter and the Philosophers Stone', year: 1997},
{id: 2, author_id: 1, title: 'Harry Potter and the Goblet of Fire', year: 2000},
{id: 3, author_id: 2, title: 'Charlie and the Chocolate Factory', year: 1964},
{id: 4, author_id: 2, title: 'James and the giant peach', year: 1961},
{id: 5, author_id: 3, title: 'Green eggs and ham', year: 1960},
{id: 6, author_id: 3, title: 'The cat in the hat', year: 1957}
I want to be able to build query to 'show me all authors that released books in the 1960s', and it return me the mongo query allows me to query, which when executed returns the following results:
{id: 2, name: 'Roald Dahl'},
{id: 3, name: 'Dr Seuss'}
I am not sure how to arrange my data, one collection of 'authors' with embedded array of 'books' documents, or two separate collections or a combination of the two?
Mongo works well with embedded documents but not sure of the capability of react-awesome-query-builder?
It appears that $elemmatch support has been added to react-awesome-query-builder so I just needed to change my !struct config to !group and voila!

Ruby -- array of hashes, getting unique values [duplicate]

This question already has answers here:
Ruby - extracting the unique values per key from an array of hashes
(2 answers)
Closed 5 years ago.
I have the following array of hashes:
persons = [
{name: 'Mark', age: 28},
{name: 'John', age: 45},
{name: 'Sam', age: 34},
{name: 'John', age: 34}
]
I want to get an array of unique values for the key name. In this case it should be ['Mark', 'John', 'Sam'].
Here is my solution:
names = []
persons.each do |person|
names << person[:name] unless names.include? person[:name]
end
Is there a better way to do it?
You can combine map and uniq:
persons = [
{name: 'Mark', age: 28},
{name: 'John', age: 45},
{name: 'Sam', age: 34},
{name: 'John', age: 34}
]
persons.map { |p| p[:name] }.uniq #=> ["Mark", "John", "Sam"]
Also, you can use Set here:
require 'set'
persons.each_with_object(Set.new) { |person, set| set << person[:name] }.to_a
#=> ["Mark", "John", "Sam"]
Or by using hash:
persons.group_by { |p| p[:name] }.keys
#=> ["Mark", "John", "Sam"]

Create and Connect nodes just by using "from" and "to" info in React

I am trying to create and connect some nodes using the array below. So in the end there would be 4 nodes connected to each other according to their from and to values. Any ideas on how to do it in React?
roads = [
{
id: 1,
from: {id: 111, name: “Company X”},
to: {id: 222, name: “Station 1“}
},
{
id: 2,
from: {id: 222, name: “Station 1“},
to: {id: 333, name: “Station 2“}
},
{
id: 3,
from: {id: 333, name: “Station 2”},
to: {id: 444, name: “Company Y”}
}
]
I think , you should use Normalized State. It's easy way to create your Nodes ^^

Resources