Delete Contents of Array Based on a Set of Indexes

Delete contents of array based on a set of indexes

One-liner:

arr.delete_if.with_index { |_, index| set.include? index }

How to remove more than one elements from an array from different indexes at same time in JavaScript?

You can use trailing comma at destructuring assignment to select specific elements from array, assign resulting values within array to original array reference.

var array = [1,2,3,4,5];

{let [a,b,,c,,] = array; array = [a,b,c]};

console.log(array);

Remove all items after an index

Use Array.length to set a new size for an array, which is faster than Array.splice to mutate:

var array = ['mario','luigi','kong', 1, 3, 6, 8];
array.length=2;
alert(array); // shows "mario,luigi";

Why is it faster? Because .splice has to create a new array containing all the removed items, whereas .length creates nothing and "returns" a number instead of a new array.

To address .splice usage, you can feed it a negative index, along with a huge number to chop off the end of an array:

var array = ['mario','luigi','kong'];
array.splice(-1, 9e9);
alert(array); // shows "mario,luigi";

How to delete in array by index?

My answer involves resolution of the problem, but not what you asked in specific. This is one of the best place, a 'Map' data-type is suitable to use. Hence, I will place a small example to show the operation -

let socketStore = new Map();
//when you have something to store - a socketId and data
socketStore.set(socketId, data)
// when you want to delete the socketId
socketStore.delete(socketId)

A very nice reference to Map - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

Delete elements from python array with given index of elements as list

This question already has an answer here. How to delete elements from a list using a list of indexes?.

BTW this will do for you

x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]

index_list = [0, 4, 11]

value_list = []
for element in index_list:
value_list.append(x[element])

for element in value_list:
x.remove(element)

print(x)

Delete rows at select indexes from a numpy array

To delete indexed rows from numpy array:

arr = np.delete(arr, indexes, axis=0)


Related Topics



Leave a reply



Submit