1

I have a multidimensional array, like this:

[
    [ 
        { name: "jeff", job: "cleaner" }, 
        { name: "kate", job: "cashier" } 
    ],
    [ 
        { name: "alice", job: "engineer" },
        { name: "sean", job: "writer" },
        { name: "ruby", job: "police officer" }
    ],
    [ 
        { name: "sarah", job: "writer" }, 
        { name: "john", job: "cleaner" } 
    ]
]

I'm looking for a fast and concise way to find an object within this structure where one of the properties matches a certain value and then remove that object entirely.

For example, say I want to find all objects where the property of job is writer and remove those objects from the structure.

Please bare in mind that I would like keep the current structure of this array completely intact, with just the relevant objects removed.

9
  • Array.prototype.filter() is your friend, though it does not edit in place - otherwise check _.remove, to be iterated on every entry of the outermost array. Commented May 17, 2015 at 18:26
  • What is the purpose of the outer array? Will the relevant inner array always be at [0]? Commented May 17, 2015 at 18:27
  • @DylanWatt The structure represents rows and columns. And yes, all the inner arrays will always be at that level - the structure will not get any deeper. Commented May 17, 2015 at 18:30
  • Seems simple enough. Where are you stuck? Commented May 17, 2015 at 18:31
  • 1
    @shrewdbeans If you have enough nodes that you need to consider performance, you would want to look into maintaining a lookup map. {cleaner:[], writer:[]} etc. That would allow fast lookup of each job, and the entities that contain it. However, how the lookup map is created/maintained is still an issue. In general, you have to get pretty large to need to do this. Javascript is amazing at arrays, I've dealt with 1 million+ sized arrays client side, and it handled it like a champ on modern CPU/browsers. Commented May 17, 2015 at 19:23

1 Answer 1

2

I used a hasOwnProperty function which I do not take credit for from this question.

You can do it like this, using that function:

arr.forEach(function (subArr, index, myArr) {
    myArr[index] = subArr.filter(function (obj) {
        if (hasOwnProperty(obj, "job") && obj["job"] === "writer") {
            return false;
        }
        return true;
    });
});

Fiddle

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

1 Comment

shorter: return !(hasOwnProperty(obj, "job") && obj["job"] === "writer")

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.