javascriptarraysobjectfilterdefineproperty

How to get filtered array with defineProperty JS?


I've tried looking for a way of doing it but found none.

I want to filter out array items when I'm accessing the array. For example: filter out only negative values

let arr = [-1, -2, -4, -5, 8, 9, 10, -7, 5, 7, 8, 4, -12];
let o = {
  arr: arr
};

Object.defineProperty(o, 'arr', {
  get: () => { /* filter only negative values */ }
});

// should print only positive values
console.log(o.arr)


Solution

  • You can use filter

    let arr = [-1, -2, -4, -5, 8, 9, 10, -7, 5, 7, 8, 4, -12];
    let o = {
      array: arr
    };
    
    Object.defineProperty(o, 'arr', {
      get: () => {
        return o.array.filter(a => a >= 0)
      }
    });
    
    console.log(o.arr)