Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete elements from array that are at indexes in another array

Tags:

arrays

ruby

I have two arrays, one with data and one with indexes. I want to know if there are some good ways to delete the elements in data at the position given in indexes. I could do simple iteration but I am wondering what the shortest way is:

data = ['a','b','c','a','b','c','a','b','c']
indexes = [2,5,8]

//some code here

Elements in data are gone when the indexes happened to coincide with numbers in array indexes. It should look like this:

['a','b','a','b','a','b']
like image 916
Muhammad Umer Avatar asked Aug 24 '15 15:08

Muhammad Umer


People also ask

How do I remove from an array those elements that exists in another array?

To remove elements contained in another array, we can use a combination of the array filter() method and the Set() constructor function in JavaScript.

How do you get the elements of one array which are not present in another array using JavaScript?

Use the . filter() method on the first array and check if the elements of first array are not present in the second array, Include those elements in the output.

How do I remove a specific index from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.


1 Answers

data.values_at(*data.each_index.to_a - indexes)
# => ["a", "b", "a", "b", "a", "b"]
like image 189
sawa Avatar answered Nov 10 '22 15:11

sawa