1
['string1', 'string2'].join(',') // "string1,string2"

How can I obtain the following result?

"string1", "string2"

I am using underscore and jquery.

My goal is to make something like that:

_.without(['string1', 'string2', 'string3'], "string1", "string2");
=> ['string3']
3
  • 2
    This is very confusing, it looks like you are trying to get what you already have... Commented Nov 26, 2012 at 15:36
  • 1
    Are you positive what you really want is a list? it looks like instead you want to pass arguments to a function, which a list would be useless for. Commented Nov 26, 2012 at 15:37
  • Not sure I get it, is This it ? Commented Nov 26, 2012 at 15:41

5 Answers 5

2

For you case you don't need a "free" list of elements.
You just need to use _.difference instead of _.without.

  _.difference(['string1', 'string2', 'string3'], ["string1", "string2"]);
Sign up to request clarification or add additional context in comments.

Comments

2

You can't have a "free" list of elements. That's not how Javascript works. You always deal with arrays, collections and that sort of things.

I don't know Underscore.js very well, but try this:

var a = ['string1', 'string2', 'string3'],
    b = ['string1', 'string2'];
_.without.apply(_, [a].concat(b));

The purpose of apply is to call a function with a dynamical number of dynamic arguments.

1 Comment

1

you could get it like this:

var something = '"' + ['string1', 'string2'].join('", "') + '"';

wich would result in: "string1", "string2"

alternately you could use JSON.stringify(['string1', 'string2'])

wich would result in: ["string1","string2"]

Comments

0

another way is to write a simple function which removes an array of strings from another, sth like

var arr = ["str1","str2","str3"];

   function removeStrings(a,strs) {
     strs.forEach(function(e) {
       a.splice(a.indexOf(e),1);
     });
   }

removeStrings(arr,["str2","str1"]);
console.log(arr);//["str3"]

Comments

0

difference looks like better fit http://underscorejs.org/#difference

var rem, orig, val;
rem = ['string1', 'string2'];
orig = ['string1', 'string2', 'string3'];

val = _.difference(orig, rem); // ['string3'];

http://jsbin.com/eyegoh/1/edit

or little bit longer with jQuery using http://api.jquery.com/jQuery.grep/ and http://api.jquery.com/jQuery.inArray/

var rem, orig, val;
rem = ['string1', 'string2'];
orig = ['string1', 'string2', 'string3'];

val = $.grep(orig, function(el, ix) {
    return $.inArray(el, rem) == -1;
});

http://jsbin.com/uhihid/1/edit

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.