Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Array.exclude and array parameter #95

Closed
nazar opened this Issue · 5 comments

3 participants

@nazar

Hi there.

I'm not sure if this is the expected behaviour from sugar but I thought I'd just ask.

var a = ['1','2','3'];
var b = ['1','2']

I was expecting the following:

var c = a.exclude(b);
c = ['3']  <-- expected
c = ['1','2','3'] <-- actual

Oddly enough, this works:

var c = a.exclude('1','2')
c = ['3'] <-- as expected

Is this the expected behaviour or am I having a brain fart moment (with apologies if I am).

Is there any workaround in subtracting one array from another?

Thanks in advance and even greater thanks for a truly wonderful library.

@nazar

I should probably be doing it this way:

var a = ['1','2','3'], b = ['1','2'], c;

c = a.exclude(function(n) {
  return b.indexOf(n) !== -1;
})
@andrewplummer

Here exclude is "excluding elements from an array". Note that remove "removes elements from an array", but in a destructive way, whereas exclude does exactly the same non destructively. So what you essentially are saying is "remove the array ['1','2'] from ['1','2','3'], which doesn't exist. However if you said a.exclude('1'), the element would properly be removed.

The reason the second example works is that exclude and remove both take an unlimited number of arguments for convenience, so you're basically doing the operation twice, once on '1', and once on '2'. Note the difference here from trying to remove ['1','2'].

However subtract might closer to what you're looking for as it subtracts arrays from other arrays... try this out a.subtract(b).

If there are some points in the docs that are unclear about this please let me know and I'll fix them.

@nazar

Thanks for the clarification Andrew.

I was indeed having a serious brain fart moment. subtract is indeed what I need and I should have picked that up from the docs. Very sorry for using up your time.

@nazar nazar closed this
@andrewplummer

No worries! They're quite similar and I expect may lead to a bit of confusion for people....

@cowwoc

Andrew,

I also made this mistake (and spent a lot of time tracking down the problem in my code). Could you please mention subtract in the exclude function? Perhaps something along the lines of "see subtract to remove the contents of one array from another".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.