我怎么能只保留符合特定条件的数组项目
How can I only keep items of an array that match a certain condition?
我有一个数组,我想过滤它以仅包含与特定条件匹配的项目。这可以在JavaScript中完成吗?
一些例子:
[1, 2, 3, 4, 5, 6, 7, 8] // I only want [2, 4, 6, 8], i.e. the even numbers
["This", "is", "an", "array", "with", "several", "strings", "making", "up", "a", "sentence."] // I only want words with 2 or fewer letters: ["is", "an", "up", "a"]
[true, false, 4, 0, "abc", "", "0"] // Only keep truthy values: [true, 4, "abc", "0"]
为此,您可以使用 ECMAScript5 中引入的 Array#filter()
方法。除IE8及更低版本以及Firefox的古老版本外,所有浏览器都支持它。无论出于何种原因,如果需要支持这些浏览器,则可以对该方法使用 polyfill。
filter()
将函数作为其第一个参数。对于数组的每个项目,您的函数都会传递三个参数 - 当前项的值、它在数组中的索引和数组本身。如果您的函数返回 true
(或真值,例如 1
、"pizza"
或42
),该项目将包含在结果中。否则,它不会。 filter()
返回一个新数组 - 您的原始数组将保持不变。这意味着您需要将值保存在某个位置,否则它将丢失。
现在,在问题的例子中:
var myNumbersArray = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(myNumbersArray.filter(function(num){
return !(num % 2); // keep numbers divisible by 2
}));
console.log(myNumbersArray); // see - it hasn't changed!
var myStringArray = ["This", "is", "an", "array", "with", "several", "strings", "making", "up", "a", "sentence."];
console.log(myStringArray.filter(function(str){
return str.length < 3; // keep strings with length < 3
}));
console.log(myStringArray);
var myBoolArray = [true, false, 4, 0, "abc", "", "0"];
console.log(myBoolArray.filter(Boolean));
// wow, look at that trick!
console.log(myBoolArray);
为了完整起见,一个也使用索引和数组参数的示例: 从数组中删除重复项:
var myArray = [1,1,2,3,4,5,6,1,2,8,2,5,2,52,48,123,43,52];
console.log(myArray.filter(function(value, index, array) {
return array.indexOf(value) === index;
}));
要过滤不是严格数组的条目,因此在其原型上没有 .filter
属性,但仍可迭代(如 document.getElementsByTagName
),您可以使用
Array.prototype.filter.call(collection, function filterFunction(el, index, collection) {
...
});
或速记
[].filter.call(collection, function filterFunction(el, index, collection) {
...
});
至于不可迭代的对象,但你仍然想过滤属性并获取一个通过过滤的键数组,你可以像这样与Object.keys
组合:
var obj = { one: 1, two: 2, three: 3, four: 4 };
var filtered = Object.keys(obj).filter(function(key) {
return obj[key] % 2 === 0;
}); //filtered == ['two', 'four']
然后,您可以创建一个包含这些属性的新对象:
var filteredObj = filtered.reduce(function(newObj, currentKey) {
newObj[currentKey] = obj[currentKey]; //Add the original value to the new object
return newObj; //Return the new object to continue iteration
}, {}) // Begin iteration with a blank object
//filteredObj is now { two: 2, four: 4 }
以上甚至可以组合成一个功能!
function filterObject(obj, testCallback) {
return Object.keys(obj).filter(function(key, index, array) {
return testCallback(obj[key], index, array); //Call original filter but pass the property
}).reduce(function(newObj, currentKey) {
newObj[currentKey] = obj[currentKey]; //Add the original value to the new object
return newObj; //Return the new object to continue iteration
}, {}); // Begin iteration with a blank object
}
并像这样使用:
var obj = { one: 1, two: 2, three: 3, four: 4 };
var filteredObj = filterObject(obj, function(el) { return el % 2 === 0 });
在
@Scimonster 中使用 ES6 语法的答案之后,更简洁的答案是:
// even numbers
const even = [1, 2, 3, 4, 5, 6, 7, 8].filter(n => n%2 == 0);
// words with 2 or fewer letters
const words = ["This", "is", "an", "array", "with", "several", "strings", "making", "up", "a", "sentence."].filter(el => el.length <= 2);
// truable elements
const trues = [true, false, 4, 0, "abc", "", "0"].filter(v => v);
console.log(even);
console.log(words);
console.log(trues);
相关文章:
- 从json数组中查找满足条件的特定元素的值
- 使用restangular从json对象数组中获取具有特定条件的json对象
- 对象的数组列表的Javascript排序列表-基于特定的数组列表
- 使用具有特定条件的 lodash 添加和组合对象数组中的重复项
- 如何从 javascript 中的 foreach 循环中删除特定的数组元素
- 使用 Javascript 更改特定的数组值
- 我需要帮助让Javascript读取HTML表单,并将其分配给特定的数组
- 如何在 JavaScript 中加入(特定)数组
- Javascript:在特定的数组结构上使用array.sort()
- 在一个对象的Javascript数组中,如果一个特定的数组元素本身就是一个对象数组,我如何通过名称/ID来定位该元素
- 如何针对特定的数组值测试正则变量
- AJAX-在post中获取特定的数组值
- 正在从多维数组中删除特定的数组元素
- 获取特定的数组值
- 使用jQuery或JavaScript计算特定的数组值
- 求和特定的数组值取决于其他数组的索引值列表
- 将Json数据转换为特定的数组
- 在php中获取特定的数组字段长度
- 如何在参数上使用.reduce()而不是特定的数组或对象
- Javascript -通过键获取特定JSON数组元素中属性的值