Remove / delete values ​​in an array at specific indices

I have an array like this:

peoples = ['dick', 'jane', 'harry', 'debra', 'hank', 'frank' .... ] 

And one of them contains such keys:

 keys = [1, 6, 3, 12 .... ] 

Now I could write something like this:

 var peoplesStripedOfKeyPostions = []; for(i = 0; i < peoples.length; i++){ for(j = 0; j < keys.length; j++){ if( i !== keys[j]){ peoplesStripedOfKeyPostions.push( peoples[i] ); } } } 

If you cannot say, I need to create an array of people who are deprived of people in certain positions defined in the keys of the array. I know that there must be a great and effective way to do this, but of course I can’t think about it. (array management is not my forte).

Do you know the best way to do this? (If I get some working answers, jsperf determines the winner.)

+4
source share
2 answers
 people.filter(function(x,i){return badIndices.indexOf(i)==-1}) 

This will become ineffective if the badIndices array badIndices large. A more efficient (albeit less elegant) version:

 var isBadIndex = {}; badIndices.forEach(function(k){isBadIndex[k]=true}); people.filter(function(x,i){return !isBadIndex[i]}) 

(note: you cannot use a variable called keys because it is a built-in function)

+6
source

You can simply delete entries from the array by index, and then collect anyone else.

 keys.forEach(function(i) { delete people[i]; }); peopleRemaining = Object.keys(people).map(function(i) { return people[i]; }); 

Note that this modifies the original people array.

+1
source

Source: https://habr.com/ru/post/1432854/


All Articles