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.

6
  • 1
    Do you want to mutate the object or create a new one? Commented Aug 24, 2020 at 17:42
  • @trincot yes! i am fine with that. Commented Aug 24, 2020 at 17:43
  • 3
    It was an or-question...? You mean "yes mutate" or "yes new"? Commented Aug 24, 2020 at 17:43
  • 2
    From the looks of it (not keeping the key value paring and keys always being consecutive numbers that start at 0). You should probably use an array. Commented Aug 24, 2020 at 17:44
  • @trincot my bad. create a new one would be fine Commented Aug 24, 2020 at 17:45

6 Answers 6

4
+50

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);

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

4 Comments

what should be the output if we provide input something like data = { 0: 0, 1: -1, 2: 2, 3: 4 }?
@Nithish, this: { 0: 0, 1: 2, 2: 4 }
Yes I checked that, is it intended output in that case? shouldn't it be { 0: 0, 1: 2, 2: 2, 3:4 }
afaik, op would takes keys from 0 ... n and values in order without negative values.
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);

Comments

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);

1 Comment

Added a reusable function version.
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

Comments

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)

3 Comments

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.
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.
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.
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.

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.