0

This fiddle shows how to grab the elements not in an array based upon the value of a key 9in my case id).

http://jsfiddle.net/wgmz40ow/

This solution was taken from here: Difference between two array of objects in JavaScript

Before finding that solution I attempted to use simple for loops to end up with an array that consisted ONLY of objects in a but NOT in b.

Could someone provide the solution without using javascripts Array.prototype.filter function?

Edit: In my case I specifically wanted to handle a case an array b is always a subset of an array a.

I was running into trouble with a nested loop, but once I broke the inner loop out into a function I was able to grab the solution very quickly:

http://jsfiddle.net/xzy9Lyr0/

Unfortunately, I see why the other solution is preferable - mine won't return a true difference, only the elements in a and not in b, unless I concat the two returned arrays (http://jsfiddle.net/xzy9Lyr0/2/).

Community
  • 1
  • 1
Squadrons
  • 2,467
  • 5
  • 25
  • 36
  • 2
    Trivially: write `filter`. Anyway, simple for loops *will* work (filter is just a fancy decoration on top of a loop that applies a selector function to the result accumulation logic) and have the same complexity, which is O(n^2). – user2864740 Sep 03 '14 at 23:22
  • 1
    Please post the code the YOU have tried with a for loop – dc5 Sep 03 '14 at 23:22
  • 2
    Most of us won't provide a ready-made solution. But we will help you solve any concrete problems you encounter if you try on your own. Right now there is no problem statement, just "give me the code". – Jon Sep 03 '14 at 23:24
  • I am using it in my app code - I wanted to figure out what other ways I could achieve the same result, and came here to see interesting solutions that I could learn from. – Squadrons Sep 04 '14 at 02:01

1 Answers1

0

Here's an answer which may contain traces of mischief.

In the interest of extending @Jon's call for understanding through learning, here's a simple yet complex solution:

var bstr = JSON.stringify(b);
for (var i = a.length - 1; i >= 0; i--) {
    if (!~bstr.indexOf(JSON.stringify(a[i]))) {
        c.push(a[i]);
    }
}

Enjoy!

EDIT: fix typo.

greg.arnott
  • 1,622
  • 17
  • 16