简体   繁体   中英

What's the fastest way to get a range of existing members from an array?

We have an array filled up like so:

const arr = [];
arr[3] = 'content3';
arr[4] = 'content4';
arr[6] = 'content6';
arr[7] = 'content7';

Now we want to get the existing items starting with index 3, ending with index 6. Here's a naive approach:

const slice = arr.slice(3,7); // ["content3", "content4", empty, "content6"]
const cleanSlice = slice.filter(a => a); // ["content3", "content4", "content6"]

Is there a way to read the range that does not include the empty members?

You could filter with a callback which returns true for every call (to get falsy elements as well). This approach does not visit sparse elements.

 const array = []; array[3] = 'content3'; array[4] = undefined; array[6] = 0; const result = array.filter(_ => true); console.log(result);

By taking an object and an array for the range, you could filter the keys and map the values.

 const data = {}; data[3] = 'content3'; data[4] = undefined; data[6] = 0; data[7] = 'content7'; const range = [3, 6]; const result = Object.keys(data).filter(k => k >= range[0] && k <= range[1]).map(k => data[k]); console.log(result);

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