0

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)
Omri Attiya
  • 3,917
  • 3
  • 19
  • 35

2 Answers2

2

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)
ptothep
  • 415
  • 3
  • 10
1

you can use Array.prototype.filter and this(context)

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

Object.defineProperty(o, 'negative', {
  // return array values where item < 0
  get: function () {return this.arr.filter(item => item < 0)}
});

// should print only positive values
console.log(o.negative)
Sergey Reus
  • 184
  • 1
  • 5