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"]
Related
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
}
I am working with Reactjs and my data looks like this:
const this.state.singlePost = [{
name: 'Johnny',
age: 20,
birthPlace: 'Germany'
},
{
name: 'Samuel',
age: 22,
birthPlace: 'France'
}
]
let this.state.post = [{
email: 'john#gm.co',
number: 4567887654
},
{
email: 'samuel#gm.co',
number: 0987655881
},
]
I want to make something like this:
let editedPost = [{
name: 'Johnny',
age: 20,
birthPlace: 'Germany',
email: 'john#gm.co',
number: 4567887654
},
{
name: 'Samuel',
age: 22,
birthPlace: 'France',
email: 'samuel#gm.co',
number: 0987655881
}
]
It might be a stupid question, but I got stuck for a few hours on this, Could somebody help me please? I have 5 items in this.state.singlePost and 10 items in this.state.post. How do I put the stuff in this.state.singlePost into this.state.post just like the way I did in editedPost?
In theory, you would have a common key between the two objects that you would be able to merge on as without you will be relying on matching the index of objects.
let post = [
{email: 'john#gm.co',
number: 4567887654},
{email: 'samuel#gm.co',
number: 987655881}
]
let singlePost = [
{name: 'Johnny', age: 20, birthPlace: 'Germany'},
{name: 'Samuel', age: 22, birthPlace: 'France'}
]
let newList = post.map((item, i) => ({...item, ...singlePost[i]}))
console.log(newList)
Output:
[
{
email:"john#gm.co",
number:4567887654,
name:"Johnny",
age:20,
birthPlace:"Germany"
},
{
email:"samuel#gm.co",
number:987655881,
name:"Samuel",
age:22,
birthPlace:"France"
}
]
There is many ways to do this in Javascript. The way I chose prevents mutation of data, which may be something you are concerned with when using React.
I'm using ngTable to display some data and I need an initial way of sorting order to display it at page load. There's the normal option to set the sorting, for example sorting: {color: "asc"}, this will sort the color column alphabetically. Assuming this is my table data:
var x = [
{name: "allen", age: 33, color:"green"},
{name: "jon", age: 23, color:"blonde"},
{name: "silver", age: 54, color:"yellow"},
{name: "james", age: 52, color:"grey"},
{name: "flint", age: 25, color:"pink"},
{name: "billy", age: 31, color:"blonde"},
{name: "bones", age: 47, color:"grey"},
{name: "michael", age: 35, color:"green"},
{name: "jackson", age: 234, color:"yellow"},
{name: "leonardo", age: 12, color:"brown"},
{name: "dicaprio", age: 73, color:"pink"},
{name: "sylvester", age: 35, color:"blonde"}
];
How can I set the initial sort order of the color column by custom order, such as first all green, then all pink then all yellow and last grey.
This is my code so far:
function demoController(NgTableParams, simpleList) {
var names = [
{name: "allen", age: 33, color:"green"},
{name: "jon", age: 23, color:"blonde"},
{name: "silver", age: 54, color:"yellow"},
{name: "james", age: 52, color:"grey"},
{name: "flint", age: 25, color:"pink"},
{name: "billy", age: 31, color:"blonde"},
{name: "bones", age: 47, color:"grey"},
{name: "michael", age: 35, color:"green"},
{name: "jackson", age: 234, color:"yellow"},
{name: "leonardo", age: 12, color:"brown"},
{name: "dicaprio", age: 73, color:"pink"},
{name: "sylvester", age: 35, color:"blonde"}
];
this.tableParams = new NgTableParams({
// initial sort order
sorting: { color: ["green","pink","yellow","grey"] }
}, {
dataset: names
});
}
Code is here.
Did you add the sort attribute in the directive?
<td title="'Name'" filter="{ name: 'text'}" sortable="'name'">
This is my angular code.
$scope.names = [
{name: 'Tobias', gender: 'm'},
{name: 'Jeff', gender: 'm'},
{name: 'Lisa', gender: 'f'},
{name: 'Diana', gender: 'f'},
{name: 'James', gender: 'm'},
{name: 'Brad', gender: 'm'}
];
$scope.filteredNames = filterFilter($scope.names, 'a');
$scope.filteredNamesByFemale = filterFilter($scope.names, {gender: 'f'});
I want to know how to chain the two filters filterFilter($scope.names, 'a') and filterFilter($scope.names, {gender: 'f'})
Pass $scope.filteredNames instead of $scope.names in the second call.
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?