1

What is the best way to check if an object has items with negative values using javascript or ES6, if that is the case remove it from the object?

foo = { 0: 0, 1: -1, 2: 2, 3: -1}

result should be the one below

foo = { 0: 0, 1: 2}

Sorry, i am coming from a python background but i would love to hear from you.

John D
  • 285
  • 3
  • 22

6 Answers6

4

You could filter the values and get a new object.

Assumptions:

  • Object contains only index like keys (32 bit positive integer values).
  • Keys starts from zero to n.
  • The order should remain constant.
  • The new object has now keys from zero to m where m <= n, depending of the count of the positive values.

The solution takes the values of the object in the standard order of ECMA-262 (Does JavaScript guarantee object property order?), filter this array and assigns the array to an object.

The result is an object with key and values from the filtered array.

const
    data = { 0: 0, 1: -1, 2: 2, 3: -1 },
    result = Object.assign({}, Object.values(data).filter(v => v >= 0));

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

You can use .filter to remove elements with negative values:

foo = { 0: 0, 1: -1, 2: 2, 3: -1}
let positives = Object.entries(foo).filter(e => e[1]>=0);
foo = {};
positives.forEach(([key, value], index) => {
     foo[index] = value;
});
console.log(foo);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
2

If you want to modify the existing object rather than make a copy, you can do this:

let foo = { 0: 0, 1: -1, 2: 2, 3: -1}
for (let [key, value] of Object.entries(foo)) {
    if (typeof value === "number" && value < 0) {
        delete foo[key];
    }
}
console.log(foo);

Note: I added the typeof value === "number" as a type-safety check so you make sure you're comparing a numeric value in case there are other types of properties.


Or, in a reusable function that can be used with a user-supplied condition:

// callback passed (key, value) and
//   return true to keep, false to remove the property
// function returns original object with desired properties removed
function filterProperties(obj, callback) {
    for (let [key, value] of Object.entries(obj)) {
        if (callback(key, value) === false) {
            delete obj[key];
        }
    }
    return obj;
}

let foo = { 0: 0, 1: -1, 2: 2, 3: -1}
filterProperties(foo, (key, value) => !(typeof value === "number" && value < 0));
console.log(foo);
jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

If you want to create a new object

const fooWithoutNegativeValues = Object.entries(foo).reduce((acc, [key, value]) => value >= 0 ? {...acc, [key]: value} : acc)

To mutate its not different

ehab
  • 7,162
  • 1
  • 25
  • 30
1

const foo = { 0: 0, 1: -1, 2: 2, 3: -1}
const result = Object.keys(foo).reduce((acc, curr) => {
    if(foo[curr] >= 0) {
        acc[curr] = foo[curr]
    }
    return acc;
}, {})

console.log(result)
Hamza Zaidi
  • 672
  • 5
  • 8
  • FYI, this makes a new object. It does not remove properties from the existing object. It also only checks to see if the value is not `-1` rather than check if it's negative. – jfriend00 Aug 24 '20 at 17:50
  • Mutating the object is against the functional programing rules and might have unintended consequences, but same logic can be use to mutate the `foo`, I updated the answer to check the negative values. – Hamza Zaidi Aug 24 '20 at 17:53
  • 1
    Objects are mutated ALL the time. Have you never assigned a property to an object? It depends entirely upon what the programming situation calls for. The OP asked "to remove negative values from the object". They didn't ask to make a copy of the object with different properties. – jfriend00 Aug 24 '20 at 18:03
0

This code will only modify the object to delete negatives.

foo = { 0: 0, 1: -1, 2: 2, 3: -1}

Object.keys(foo).map((key) => {
    if(foo[key]<0){
        delete foo[key]
    }
})

console.log(foo);

For a short explanation, Object.keys(foo) will turn the object into an array based on the key names. Then .map() loops through each key in the array, and if the condition passes, it will delete the variable.