带钢/删除在某个索引数组值 [英] Strip/remove values in array at certain indices

查看:128
本文介绍了带钢/删除在某个索引数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,像这样:

 人民= ['家伙','简','哈利','德布拉','汉克','坦率'... ...]

和含有象这样的键之一:

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

现在我可以这样写:

  VAR peoplesStripedOfKeyPostions = [];对于(i = 0; I< peoples.length;我++){
    为(J = 0; J< keys.length; J ++){
        如果(我!==键[J]){
            peoplesStripedOfKeyPostions.push(人民[我]);
        }
    }
}

如果你不能告诉,我需要制作的是在数组中的键定义某些位置被剥夺人的人的数组。我知道必须有这样做一个漂亮的和有效的方式,但我肯定不能把它。 (阵列管理不是我的专长)。

你知道一个更好的方式来做到这一点? (如果我得到多个工作答案,jsperf决定赢家。)


解决方案

  people.filter(函数(X,I){返回badIndices.indexOf(我)==  -  1})

如果在 badIndices 阵列较大,这将变得效率低下。一个更有效(尽管不那么优雅的)版本将是:

  VAR isBadIndex = {};
badIndices.forEach(函数(K){isBadIndex [K] =真});people.filter(函数(X,I){返回!isBadIndex [I]})

注:你不能用一个名为变量,因为这是一个内置函数的)

I have one array like so:

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

And one containing keys like so:

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 can't tell, I'm need to produce an array of people that is stripped of people at certain positions defined in array keys. I know there has to be a nifty and efficient way to do this, but I certainly can't think of it. (array management not my forte).

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

解决方案

people.filter(function(x,i){return badIndices.indexOf(i)==-1})

This will become inefficient if the badIndices array is large. A more efficient (albeit less elegant) version would be:

var isBadIndex = {};
badIndices.forEach(function(k){isBadIndex[k]=true});

people.filter(function(x,i){return !isBadIndex[i]})

(note: you cannot use a variable named keys because that is a builtin function)

这篇关于带钢/删除在某个索引数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆