Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
Is there a way to compare two arrays and return a new array of the common elements which have the same index?

For example

a = [2,3,1,1]
b = [2,7,4,2]

--> c = [2]

My solution was:

c = b.select do
    |em| b.index(em) == a.index(em)
    end

But if I apply it to the given example it returns

c = [2,2]
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Since you want to compare arrays element-wise, zip would be an excellent choice here.

a.zip(b) # => [[2, 2], [3, 7], [1, 4], [1, 2]]

a.zip(b).select {|a1, b1| a1 == b1}.map(&:first) # [2]

# or in ruby 2.7+
a.zip(b).filter_map {|a1, b1| a1 == b1 && a1} # [2]
over 4 years ago · Santiago Trujillo Report

0

a = [2,3,1,1]
b = [2,7,4,2]
c = b.select do |em|
  b.index(em) == a.index(em)
end

b.select do |em| takes the first element of b (which is 2). b.index(em) finds the first index which contains a 2, which is the first one. (index 0). Since array a has a 2 on the same index, the whole block is true and the element 2 is selected. But the same story is true for the last element. Again, the b array is searched and the first 2 is found at index 0. Hence, that 2 is also selected.

a.each_with_index.to_a & b.each_with_index.to_a

woud give you the common element(s) and their indices.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!