简体   繁体   中英

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. If the array contains no elements less than 100, it should return an empty array. 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

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

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.

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.

 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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