简体   繁体   English

如何从数组中获取小于 100 的所有值?

[英]How do I get all values from an Array that are less than 100?

Given an object and a key, I am creating a function that returns an array containing all the elements of the array located at the given key that are less than 100. Basically, If the array is empty, it should return an empty array.给定一个对象和一个键,我正在创建一个函数,该函数返回一个数组,该数组包含位于给定键的数组中小于 100 的所有元素。基本上,如果数组为空,则应返回一个空数组。 If the array contains no elements less than 100, it should return an empty array.如果数组不包含小于 100 的元素,则应返回一个空数组。 If the property at the given key is not an array, it should return an empty array.如果给定键的属性不是数组,则应返回一个空数组。 If there is no property at the key, it should return an empty array.如果键上没有属性,它应该返回一个空数组。

Here are my codes so far:到目前为止,这是我的代码:

 function getElementsLessThan100AtProperty(obj, key) { if (obj.key < 100) { return obj.key; } } var obj = { key: [1000, 20, 50, 500] }; var output = getElementsLessThan100AtProperty(obj, 'key'); console.log(output); // --> MUST RETURN [20, 50]

Any idea what am I missing?知道我错过了什么吗?

Use the filter method to help with this.使用过滤器方法来帮助解决这个问题。

Note: Mozilla JavaScript Docs注意: Mozilla JavaScript 文档

The filter() method creates a new array with all elements that pass the test implemented by the provided function. filter() 方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。

Something like this should do the trick:像这样的事情应该可以解决问题:

var obj = {
  key: [1000, 20, 50, 500]
};

var output = obj['key'].filter(function(item){
  return item < 100;
});

console.log(output); // --> MUST RETURN [20, 50]

The same can be shortened using the ES6 arrow function and an implicit return.同样可以使用 ES6 箭头函数和隐式返回来缩短。

var output = obj['key'].filter(item => item < 100);

Using filter with arrow function will make your code much shorter.使用带箭头函数的过滤器将使您的代码更短。

 var obj = { key: [1000, 20, 50, 500], }; console.log(obj['key'].filter(item => item < 100));

You can also use reduce to check if elements are less than 100 , then push the value to the accumulator.您还可以使用reduce检查元素是否小于100 ,然后将值推送到累加器。

 var obj = { key: [1000, 20, 50, 500], }; var output = obj['key'].reduce((acc, curr) => { if (curr < 100) acc.push(curr); return acc; }, []); console.log(output);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM