0

I have a Array of Hashes that have JSONs with duplicated fields and I want to delete the duplicated ones:

[ {
  "code" : "32F",
  "lon" : 0.963335,
  "fint" : "2022-05-03T13:00:00",
  "prec" : 0.0,
},{
  "code" : "32F",
  "lon" : 0.963335,
  "fint" : "2022-05-03T13:00:00",
  "prec" : 0.0,
},{
  "code" : "90X",
  "lon" : 0.963335,
  "fint" : "2022-05-03T13:00:00",
  "prec" : 0.0,
}]

This is the wished output:

[{
  "code" : "32F",
  "lon" : 0.963335,
  "fint" : "2022-05-03T13:00:00",
  "prec" : 0.0,
},{
  "code" : "90X",
  "lon" : 0.963335,
  "fint" : "2022-05-03T13:00:00",
  "prec" : 0.0,
}]

Any ideas?

Thanks!

mechnicov
  • 12,025
  • 4
  • 33
  • 56
Yung Sifilis
  • 120
  • 10

3 Answers3

2

First you have wrong syntax

"code" : "32F", -- you don't need whitespace here

Right variant is "code": "32F",

And you even don't need quotes here. Just code: "32F",

To delete duplicates from array -- use uniq!

Be careful

ary = [1, 1]
ary.uniq! # => [1]
ary # => [1]


ary = [1, 2]
ary.uniq! # => nil
ary # => [1, 2]

Or use uniq without bang to return new array

ary = [1, 1]
ary.uniq # => [1]
ary # => [1, 1]


ary = [1, 2]
ary.uniq # => [1, 2]
ary # => [1, 2]

In your case

ary =
  [{
    code: "32F",
    lon: 0.963335,
    fint: "2022-05-03T13:00:00",
    prec: 0.0,
  },{
    code: "32F",
    lon: 0.963335,
    fint: "2022-05-03T13:00:00",
    prec: 0.0,
  },{
    code: "90X",
    lon: 0.963335,
    fint: "2022-05-03T13:00:00",
    prec: 0.0,
  }]

ary.uniq!
# => [{:code=>"32F", :lon=>0.963335, :fint=>"2022-05-03T13:00:00", :prec=>0.0}, {:code=>"90X", :lon=>0.963335, :fint=>"2022-05-03T13:00:00", :prec=>0.0}]
mechnicov
  • 12,025
  • 4
  • 33
  • 56
  • Thanks, this work for JSON fields I posted. But If i have elements with same ```name``` and diferent ```lon``` how should do it? – Yung Sifilis May 10 '22 at 07:46
  • There is no `name` in your example. You can use `uniq` with block: `ary.uniq { |hash| hash[:name] }` – mechnicov May 10 '22 at 07:56
  • 1
    @YungSifilis if you have such elements, it's unclear which of the different `lon` values you want to keep. Or maybe you want to calculate an average in that case. Please update your question accordingly. – Stefan May 10 '22 at 11:55
  • @YungSifilis `uniq` with block will keep first duplicate – mechnicov May 10 '22 at 12:06
0

Try uniq from the enumerables module. It should work natively for your use case. It's available by default with a ruby array.

deibele1
  • 51
  • 2
-1

use .uniq this should work for you. NB: Your array of hashes having additional space after each key. You should remove it.

Crazy Cat
  • 186
  • 3
  • 13