Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove array elements that are present in another array

There is a list of words and list of banned words. I want to go through the word list and redact all the banned words. This is what I ended up doing (notice the catched boolean):

puts "Give input text:"
text = gets.chomp
puts "Give redacted word:"
redacted = gets.chomp

words = text.split(" ")
redacted = redacted.split(" ")
catched = false

words.each do |word|
  redacted.each do |redacted_word|
    if word == redacted_word
        catched = true
        print "REDACTED "
        break
    end
  end
    if catched == true
        catched = false
    else
        print word + " "
    end
end

Is there any proper/efficient way?

like image 317
Mikko Vedru Avatar asked May 05 '15 11:05

Mikko Vedru


People also ask

How do you remove common elements from two arrays?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.

How do you remove an element from an array from another array in Python?

Removing Array Elements You can use the pop() method to remove an element from the array.

How do you remove all elements of an array from another array in JavaScript?

Array elements can be deleted using the JavaScript operator delete . Using delete leaves undefined holes in the array. Use pop() or shift() instead.


2 Answers

You can use .reject to exclude all banned words that are present in the redacted array:

words.reject {|w| redacted.include? w}

Demo

If you want to get the list of banned words that are present in the words array, you can use .select:

words.select {|w| redacted.include? w}

Demo

like image 72
potashin Avatar answered Oct 15 '22 22:10

potashin


It also can works.

words - redacted

+, -, &, these methods are very simple and useful.

irb(main):016:0> words = ["a", "b", "a", "c"]
=> ["a", "b", "a", "c"]
irb(main):017:0> redacted = ["a", "b"]
=> ["a", "b"]
irb(main):018:0> words - redacted
=> ["c"]
irb(main):019:0> words + redacted
=> ["a", "b", "a", "c", "a", "b"]
irb(main):020:0> words & redacted
=> ["a", "b"]
like image 26
pangpang Avatar answered Oct 15 '22 21:10

pangpang