0

Is there a way I can skip checking array length every time I want to use a filter, map, or any other method used on arrays?

const newArray = array.length ? array.filter(n=>n.id=id) : [];

const otherArray = array.length ? array.map(n=>n.id=id) : [];
1
  • 9
    You don't need to check the array length when using filter or map, you will get [] as a result if the length is 0.. Commented Aug 27, 2019 at 14:29

5 Answers 5

6

You don't have to check them.

const testArr = [];

const anotherArr = testArr.map((item) => { 
  // do something with item;
  return transformedItem;
});

// anotherArr is [];

const anotherArr2 = testArr.filter((item) => { 
  // do something with item;
  return boolean;
});

// anotherArr2 is still [];

Sign up to request clarification or add additional context in comments.

Comments

0

You don’t need to check the length, if array length is 0 then after the map or filter operation would give you empty array.

Here the assumption is, the array variable is an empty array but not undefined.

1 Comment

I am slow in typing and often times answers which doesn’t require code but just text I post it using mobile application. Sorry.
0

The callback is invoked for each element of the array. If there is no element, it won't be invoked.

Just don't check it :

const array = [];
const id = 42;

const newArray = array.filter(n => n.id === id);
const otherArray = array.map(n => n.id = id);

console.log(newArray);
console.log(otherArray);

[].forEach(elem => console.log("Hello world ")); // no output

Comments

0

You don't need to do anything, just call a function .map() or .filter() etc..It returns empty array( []) if nothing return.

const array = [];
const mapped = array.map(() => {})
console.log(mapped);

1 Comment

it's usually a good idea to check the other answers before posting - this same answer was already given twice.
0

You can try something similar to:

const newArray = array.length && array.filter(n=> n.id === id);

Or you can create a wrapper method and have a logic in that returns array on which you can further modify as per your logic.

function isArrayValid(array, callback) {
  if (Array.isArray(array)) {
      return callback(array);
  }
  return [];
}


const newArray = isArrayValid(array, (_validArray) => {
 return _validArray.filter(n => n.id === id);
});

const otherArray = isArrayValid(array, (_validArray) => {
 return _validArray.map(n => n.id * 2);
});

Hope it helps. Happy coding !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.