Rectangle 27 30

Elegant way to fill an array with precomputed values

Here is another way to do it using ES6 that nobody has mentioned so far:

> Array.from(Array(3), () => 0)
< [0, 0, 0]

It works by passing a map function as the second parameter of Array.from.

In the example above, the first parameter allocates an array of 3 positions filled with the value undefined and then the lambda function maps each one of them to the value 0.

Array(len).fill(0)

For instance, if you need an array with 10 random numbers:

> Array.from(Array(10), () => Math.floor(10 * Math.random()))
< [3, 6, 8, 1, 9, 3, 0, 6, 7, 1]
const numbers = Array(10);
for (let i = 0; i < numbers.length; i++) {
    numbers[i] = Math.round(10 * Math.random());
}

This method can also be used to generate sequences of numbers by taking advantage of the index parameter provided in the callback:

> Array.from(Array(10), (d, i) => i)
< [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Since this answer is getting a good deal of attention, I also wanted to show this cool trick. Although not as useful as my main answer, will introduce the still not very known, but very useful String repeat() method. Here's the trick:

> "?".repeat(10).split("").map(() => Math.floor(10 * Math.random()))
< [5, 6, 3, 5, 0, 8, 2, 7, 4, 1]

Cool, huh? repeat() is a very useful method to create a string that is the repetition of the original string a certain number of times. After that, split() creates an array for us, which is then map()ped to the values we want. Breaking it down in steps:

> "?".repeat(10)
< "??????????"

> "?".repeat(10).split("")
< ["?", "?", "?", "?", "?", "?", "?", "?", "?", "?"]

> "?".repeat(10).split("").map(() => Math.floor(10 * Math.random()))
< [5, 6, 3, 5, 0, 8, 2, 7, 4, 1]

Most efficient way to create a zero filled JavaScript array? - Stack O...

javascript arrays
Rectangle 27 12

Find duplicate values in an array

This should be one of the shortest ways to actually find duplicate values in an array. As specifically asked for by the OP, this does not remove duplicates but finds them.

var input = [1, 2, 3, 1, 3, 1];

var duplicates = input.reduce(function(acc, el, i, arr) {
  if (arr.indexOf(el) !== i && acc.indexOf(el) < 0) acc.push(el); return acc;
}, []);

document.write(duplicates); // = 1,3 (actual array == [1, 3])

This doesn't need sorting or any third party framework. It also doesn't need manual loops. It works with every value indexOf() (or to be clearer: the strict comparision operator) supports.

Because of reduce() and indexOf() it needs at least IE 9.

Easiest way to find duplicate values in a JavaScript array - Stack Ove...

javascript arrays
Rectangle 27 12

Find duplicate values in an array

This should be one of the shortest ways to actually find duplicate values in an array. As specifically asked for by the OP, this does not remove duplicates but finds them.

var input = [1, 2, 3, 1, 3, 1];

var duplicates = input.reduce(function(acc, el, i, arr) {
  if (arr.indexOf(el) !== i && acc.indexOf(el) < 0) acc.push(el); return acc;
}, []);

document.write(duplicates); // = 1,3 (actual array == [1, 3])

This doesn't need sorting or any third party framework. It also doesn't need manual loops. It works with every value indexOf() (or to be clearer: the strict comparision operator) supports.

Because of reduce() and indexOf() it needs at least IE 9.

javascript - Get all non-unique values (i.e.: duplicate/more than one ...

javascript arrays
Rectangle 27 526

Provided your arrays are not huge (see caveat below), you can use the push() method of the array to which you wish to append values. push() can take multiple parameters so you can use its apply() method to pass the array of values to be pushed as a list of function parameters. This has the advantage over using concat() of adding elements to the array in place rather than creating a new array.

However, it seems that for large arrays (of the order of 100,000 members or more), this trick can fail. For such arrays, using a loop is a better approach. See https://stackoverflow.com/a/17368101/96100 for details.

var newArray = [];
newArray.push.apply(newArray, dataArray1);
newArray.push.apply(newArray, dataArray2);

You might want to generalize this into a function:

function pushArray(arr, arr2) {
    arr.push.apply(arr, arr2);
}
Array

... or emulate the original push() method by allowing multiple parameters using the fact that concat(), like push(), allows multiple parameters:

Here's a loop-based version of the last example, suitable for large arrays and all major browsers, including IE <= 8:

Array.prototype.pushArray = function() {
    var toPush = this.concat.apply([], arguments);
    for (var i = 0, len = toPush.length; i < len; ++i) {
        this.push(toPush[i]);
    }
};
newArray.push.apply(newArray, dataArray1);
Array.prototype.push.applay(newArray,dataArra1);

push.apply whas exacly what I was looking for, thx

Thank you very much for this solution! may I ask if there is something reverse? like removing an entire array from another?

Javascript push array values into another array - Stack Overflow

javascript arrays
Rectangle 27 526

Provided your arrays are not huge (see caveat below), you can use the push() method of the array to which you wish to append values. push() can take multiple parameters so you can use its apply() method to pass the array of values to be pushed as a list of function parameters. This has the advantage over using concat() of adding elements to the array in place rather than creating a new array.

However, it seems that for large arrays (of the order of 100,000 members or more), this trick can fail. For such arrays, using a loop is a better approach. See https://stackoverflow.com/a/17368101/96100 for details.

var newArray = [];
newArray.push.apply(newArray, dataArray1);
newArray.push.apply(newArray, dataArray2);

You might want to generalize this into a function:

function pushArray(arr, arr2) {
    arr.push.apply(arr, arr2);
}
Array

... or emulate the original push() method by allowing multiple parameters using the fact that concat(), like push(), allows multiple parameters:

Here's a loop-based version of the last example, suitable for large arrays and all major browsers, including IE <= 8:

Array.prototype.pushArray = function() {
    var toPush = this.concat.apply([], arguments);
    for (var i = 0, len = toPush.length; i < len; ++i) {
        this.push(toPush[i]);
    }
};
newArray.push.apply(newArray, dataArray1);
Array.prototype.push.applay(newArray,dataArra1);

push.apply whas exacly what I was looking for, thx

Thank you very much for this solution! may I ask if there is something reverse? like removing an entire array from another?

Javascript push array values into another array - Stack Overflow

javascript arrays
Rectangle 27 1065

With JavaScript 1.6 / ECMAScript 5 you can use the native filter method of an Array in the following way to get an array with unique values:

function onlyUnique(value, index, self) { 
    return self.indexOf(value) === index;
}

// usage example:
var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter( onlyUnique ); // returns ['a', 1, 2, '1']

The native method filter will loop through the array and leave only those entries that pass the given callback function onlyUnique.

onlyUnique checks, if the given value is the first occurring. If not, it must be a duplicate and will not be copied.

This solution works without any extra library like jQuery or prototype.js.

It works for arrays with mixed value types too.

For old Browsers (<ie9), that do not support the native methods filter and indexOf you can find work arounds in the MDN documentation for filter and indexOf.

If you want to keep the last occurrence of a value, simple replace indexOf by lastIndexOf.

// usage example:
var myArray = ['a', 1, 'a', 2, '1'];
var unique = myArray.filter((v, i, a) => a.indexOf(v) === i); 

// unique is ['a', 1, 2, '1']

Thanks to Camilo Martin for hint in comment.

ES6 has a native object Set to store unique values. To get an array with unique values you could do now this:

var myArray = ['a', 1, 'a', 2, '1'];

let unique = [...new Set(myArray)]; 

// unique is ['a', 1, 2, '1']

The constructor of Set takes an iterable object, like Array, and the spread operator ... transform the set back into an Array. Thanks to Lukas Liese for hint in comment.

This solution will run much slower, unfortunately. You're looping twice, once with filter and once with index of

@JackFranzen Slower than what? The solution from Rafael? Rafaels solution do not work for mixed type arrays. For my example ['a', 1, 'a', 2, '1'] you would get ['a', 1, 2]. But this is not what I expected. BTW, much slower is very relative.

.filter((v,i,a)=>a.indexOf(v)==i)

This solution will get exponentially slower the bigger the array gets. It should not be the accepted answer.

let unique_values = [...new Set(random_array)];

javascript - Get all unique values in an array (remove duplicates) - S...

javascript arrays unique
Rectangle 27 1065

With JavaScript 1.6 / ECMAScript 5 you can use the native filter method of an Array in the following way to get an array with unique values:

function onlyUnique(value, index, self) { 
    return self.indexOf(value) === index;
}

// usage example:
var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter( onlyUnique ); // returns ['a', 1, 2, '1']

The native method filter will loop through the array and leave only those entries that pass the given callback function onlyUnique.

onlyUnique checks, if the given value is the first occurring. If not, it must be a duplicate and will not be copied.

This solution works without any extra library like jQuery or prototype.js.

It works for arrays with mixed value types too.

For old Browsers (<ie9), that do not support the native methods filter and indexOf you can find work arounds in the MDN documentation for filter and indexOf.

If you want to keep the last occurrence of a value, simple replace indexOf by lastIndexOf.

// usage example:
var myArray = ['a', 1, 'a', 2, '1'];
var unique = myArray.filter((v, i, a) => a.indexOf(v) === i); 

// unique is ['a', 1, 2, '1']

Thanks to Camilo Martin for hint in comment.

ES6 has a native object Set to store unique values. To get an array with unique values you could do now this:

var myArray = ['a', 1, 'a', 2, '1'];

let unique = [...new Set(myArray)]; 

// unique is ['a', 1, 2, '1']

The constructor of Set takes an iterable object, like Array, and the spread operator ... transform the set back into an Array. Thanks to Lukas Liese for hint in comment.

This solution will run much slower, unfortunately. You're looping twice, once with filter and once with index of

@JackFranzen Slower than what? The solution from Rafael? Rafaels solution do not work for mixed type arrays. For my example ['a', 1, 'a', 2, '1'] you would get ['a', 1, 2]. But this is not what I expected. BTW, much slower is very relative.

.filter((v,i,a)=>a.indexOf(v)==i)

This solution will get exponentially slower the bigger the array gets. It should not be the accepted answer.

let unique_values = [...new Set(random_array)];

javascript - Get all unique values in an array (remove duplicates) - S...

javascript arrays unique
Rectangle 27 948

var arr = [1,2,,3,,3,null,,0,,undefined,4,,4,,5,,6,,,,];

// (filter - JS 1.6 and above)
arr = arr.filter(function(n){ return n != undefined }); 

arr // [1, 2, 3, 3, 0, 4, 4, 5, 6]

//or - (only for arrays items which are numbers is numbers' strings)**
arr = arr.filter(Number) // [1, 3, 3, 4, 4, 5, 6]

// ES6 style (Firefox FTW)
arr.filter(n => true) // [1, 2, 3, 3, null, 0, undefined, 4, 4, 5, 6]

// or if "null" values are to be removed:
arr.filter(n => n)

or - (only for single array items of type "text")

['','1','2',3,,'4',,undefined,,,'5'].join('').split(''); 
// output:  ["1","2","3","4","5"]

or - Classic way: simple iteration

var arr = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];

arr = $.grep(arr,function(n){ return n == 0 || n });

arr // [1, 2, 3, 3, 0, 4, 4, 5, 6]
var arr = [1,2,null, undefined,3,,3,,,0,,,4,,4,,5,,6,,,,], 
    temp = [];

for(let i of arr)
    i && temp.push(i); // copy each non-empty value to the 'temp' array

arr = temp;
delete temp; // discard the variable

arr // [1, 2, 3, 3, 4, 4, 5, 6]
['foo', '',, ' ', true, [], [1], {}, undefined].filter(String)

// ["foo", " ", true, [1], Object {}, undefined]

Another method that removes the "falsey" values of empty string "", 0 and undefined

[1, 2,, 3,, 3,undefined,,"",false,null,0,NaN, 4," ", 4,true, 5,, 6,,,,].filter(Boolean);

// [1, 2, 3, 3, 4, " ", 4, true, 5, 6]

note - filter was introduced in javascript 1.6

arr = arr.filter(function(n){return n; });

foo.join("").split("") only seems to work if the strings are single characters

Your pure JavaScript code has a bug. If the array has a value with "0" in it, the value will be filtered out because "0" is falsy. What you want is: arr.filter(function (n) { return (n !== undefined && n !== null); });

Remove empty elements from an array in Javascript - Stack Overflow

javascript arrays
Rectangle 27 4

Working with returned values:

The traditional way to solve this is to add the promises to an array, then evaluate them all together using $.when.apply

As you want to keep the values, you can then access them using the arguments array:

var promise = [];
for (var i = 0; i < 6; i++){
    promise.push(delay(6-i, $('#' + i)));
}
$.when.apply($, promise).done(function(){
    $('body').append("All done!");
    for (var i = 0; i < arguments.length; i++){
        $('body').append(arguments[i]).append("<br/>");
    }
});

The following example uses a simple function that returns a promise, using a timer, to simulate ajax calls. It clearly shows the suggestion working even though the promises complete in "random" order (just to demonstrate):

  • The values are returned in the order the calls were made, not the completion order.

Little trick I found: You can chain promises in parallel with $.when without having to use an array of promises:

var promise;   // Undefined also means a resolved promise to $.when
for(...){//we don't know the number of ajax calls
   promise = $.when(promise, $.ajax({...}));
}
promise.done(function(){
   alert("All done");
});
  • I figured this one out after seeing someone chain promises sequentially, using promise = promise.then(newpromise)
  • The downside is it creates extra promise objects behind the scenes and any parameters passed at the end are not very useful (as they are nested recursively inside additional objects). If you do not require the parameters, it is short and simple.

You will note in the following fiddle that the results are nested and in the reverse order you want them. Again this technique is only useful if you do not want the results of the promises (which is quite often for parallel operations).

Summary: The $.when technique is only useful if you do not care about the result values.

So your solution is to run the ajax calls sequentially?

Oh, I misread the $.when as $.then - my mistake (thought $.then was some more jQuery bastardisation of the promise spec) - the question asks how can I use the results of ajax calls - seems your solution throws all the results away

@JaromandaX: Have added answer that includes processing a variable number of results.

arr= arguments[0];
arr= arguments;
promise = $.when(promise, undefined);

javascript - How can I use the results of ajax calls, made inside a lo...

javascript jquery ajax promise deferred
Rectangle 27 4

Working with returned values:

The traditional way to solve this is to add the promises to an array, then evaluate them all together using $.when.apply

As you want to keep the values, you can then access them using the arguments array:

var promise = [];
for (var i = 0; i < 6; i++){
    promise.push(delay(6-i, $('#' + i)));
}
$.when.apply($, promise).done(function(){
    $('body').append("All done!");
    for (var i = 0; i < arguments.length; i++){
        $('body').append(arguments[i]).append("<br/>");
    }
});

The following example uses a simple function that returns a promise, using a timer, to simulate ajax calls. It clearly shows the suggestion working even though the promises complete in "random" order (just to demonstrate):

  • The values are returned in the order the calls were made, not the completion order.

Little trick I found: You can chain promises in parallel with $.when without having to use an array of promises:

var promise;   // Undefined also means a resolved promise to $.when
for(...){//we don't know the number of ajax calls
   promise = $.when(promise, $.ajax({...}));
}
promise.done(function(){
   alert("All done");
});
  • I figured this one out after seeing someone chain promises sequentially, using promise = promise.then(newpromise)
  • The downside is it creates extra promise objects behind the scenes and any parameters passed at the end are not very useful (as they are nested recursively inside additional objects). If you do not require the parameters, it is short and simple.

You will note in the following fiddle that the results are nested and in the reverse order you want them. Again this technique is only useful if you do not want the results of the promises (which is quite often for parallel operations).

Summary: The $.when technique is only useful if you do not care about the result values.

So your solution is to run the ajax calls sequentially?

Oh, I misread the $.when as $.then - my mistake (thought $.then was some more jQuery bastardisation of the promise spec) - the question asks how can I use the results of ajax calls - seems your solution throws all the results away

@JaromandaX: Have added answer that includes processing a variable number of results.

arr= arguments[0];
arr= arguments;
promise = $.when(promise, undefined);

javascript - How can I use the results of ajax calls, made inside a lo...

javascript jquery ajax promise deferred
Rectangle 27 1105

To just merge the arrays (without removing duplicates) use Array.concat:

Since there is no 'built in' way to remove duplicates (ECMA-262 actually has Array.forEach which would be great for this), we have to do it manually:

Array.prototype.unique = function() {
    var a = this.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(a[i] === a[j])
                a.splice(j--, 1);
        }
    }

    return a;
};
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
// Merges both arrays and gets unique items
var array3 = array1.concat(array2).unique();

This will also preserve the order of the arrays (i.e, no sorting needed).

Since many people are annoyed about prototype augmentation of Array.prototype and for in loops, here is a less invasive way to use it:

function arrayUnique(array) {
    var a = array.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(a[i] === a[j])
                a.splice(j--, 1);
        }
    }

    return a;
}

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
    // Merges both arrays and gets unique items
var array3 = arrayUnique(array1.concat(array2));

For those who are fortunate enough to work with browsers where ES5 is available, you can use Object.defineProperty like this:

Object.defineProperty(Array.prototype, 'unique', {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function() {
        var a = this.concat();
        for(var i=0; i<a.length; ++i) {
            for(var j=i+1; j<a.length; ++j) {
                if(a[i] === a[j])
                    a.splice(j--, 1);
            }
        }

        return a;
    }
});

Note that this algorithm is O(n^2).

Let [a, b, c] and [x, b, d] be the arrays (assume quotes). concat gives [a, b, c, x, b, d]. Wouldn't the unique()'s output be [a, c, x, b, d]. That doesn't preserve the order I think - I believe OP wants [a, b, c, x, d]

OP accepted the first answer that got him working and signed off it seems. We are still comparing each others' solutions, finding-n-fixing faults, improving performance, making sure its compatible everywhere and so on... The beauty of stackoverflow :-)

I originally up-voted this but have changed my mind. Assigning prototypes to Array.prototype has the consequences of breaking "for ... in" statements. So the best solution is probably to use a function like this but not assign it as a prototype. Some people may argue that "for ... in" statements shouldn't be used to iterate array elements anyway, but people often use them that way so at the very least this solution be used with caution.

you should always use for ... in with hasOwnProperty in which case the prototype method is fine

How to merge two arrays in JavaScript and de-duplicate items - Stack O...

javascript arrays merge
Rectangle 27 1092

To just merge the arrays (without removing duplicates) use Array.concat:

Since there is no 'built in' way to remove duplicates (ECMA-262 actually has Array.forEach which would be great for this), we have to do it manually:

Array.prototype.unique = function() {
    var a = this.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(a[i] === a[j])
                a.splice(j--, 1);
        }
    }

    return a;
};
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
// Merges both arrays and gets unique items
var array3 = array1.concat(array2).unique();

This will also preserve the order of the arrays (i.e, no sorting needed).

Since many people are annoyed about prototype augmentation of Array.prototype and for in loops, here is a less invasive way to use it:

function arrayUnique(array) {
    var a = array.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(a[i] === a[j])
                a.splice(j--, 1);
        }
    }

    return a;
}

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
    // Merges both arrays and gets unique items
var array3 = arrayUnique(array1.concat(array2));

For those who are fortunate enough to work with browsers where ES5 is available, you can use Object.defineProperty like this:

Object.defineProperty(Array.prototype, 'unique', {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function() {
        var a = this.concat();
        for(var i=0; i<a.length; ++i) {
            for(var j=i+1; j<a.length; ++j) {
                if(a[i] === a[j])
                    a.splice(j--, 1);
            }
        }

        return a;
    }
});

Note that this algorithm is O(n^2).

Let [a, b, c] and [x, b, d] be the arrays (assume quotes). concat gives [a, b, c, x, b, d]. Wouldn't the unique()'s output be [a, c, x, b, d]. That doesn't preserve the order I think - I believe OP wants [a, b, c, x, d]

OP accepted the first answer that got him working and signed off it seems. We are still comparing each others' solutions, finding-n-fixing faults, improving performance, making sure its compatible everywhere and so on... The beauty of stackoverflow :-)

I originally up-voted this but have changed my mind. Assigning prototypes to Array.prototype has the consequences of breaking "for ... in" statements. So the best solution is probably to use a function like this but not assign it as a prototype. Some people may argue that "for ... in" statements shouldn't be used to iterate array elements anyway, but people often use them that way so at the very least this solution be used with caution.

you should always use for ... in with hasOwnProperty in which case the prototype method is fine

How to merge two arrays in JavaScript and de-duplicate items - Stack O...

javascript arrays merge
Rectangle 27 625

To pass an array of values to any function that normally expects them to be separate parameters, use Function.prototype.apply, so in this case you need:

$.when.apply($, my_array).then( ___ );

In ES6, you can use the ... spread operator instead:

$.when(...my_array).then( ___ );

In either case, since it's unlikely that you'll known in advance how many formal parameters the .then handler will require, that handler would need to process the arguments array in order to retrieve the result of each promise.

This works, awesome. :) I'm amazed I wasn't able to dredge up such a simple change via Google!

that's because it's a generic method, not specific to $.when - f.apply(ctx, my_array) will call f with this == ctx and the arguments set to the contents of my_array.

@Alnitak: I'm a little embarrassed that I didn't know about that method, considering how long I've been writing JavaScript now!

FWIW, the link in Eli's answer to an earler question with discussion of passing $ vs null as the first parameter is worth a read. In this particular case it doesn't matter, though.

@Alnitak: Yes, but $ is less typing than null and you're safe when $.when implementation changes (not that it's likely in this case but why not keep this unchanged by default).

javascript - Pass in an array of Deferreds to $.when() - Stack Overflo...

javascript jquery argument-passing jquery-deferred .when
Rectangle 27 235

Short explanation of the ~ tilde shortcut:

Put your values into an array, and check if your item is in the array:

if ([1, 2, 3, 4].includes(test.type)) {
    // Do something
}

If a browser you support doesn't have the Array#includes method, you can use this polyfill.

Update: Since we now have the includes method, there's no point in using the ~ hack anymore. Just keeping this here for people that are interested in knowing how it works and/or have encountered it in other's code.

Instead of checking if the result of indexOf is >= 0, there is a nice little shortcut:

if ( ~[1, 2, 3, 4].indexOf(test.type) ) {
    // Do something
}

How does this work? If an item is found in the array, indexOf returns its index. If the item was not found, it'll return -1. Without getting into too much detail, the ~ is a bitwise NOT operator, which will return 0 only for -1.

I like using the ~ shortcut, since it's more succinct than doing a comparison on the return value. I wish JavaScript would have an in_array function that returns a Boolean directly (similar to PHP), but that's just wishful thinking (Update: it now does. It's called includes. See above). Note that jQuery's inArray, while sharing PHP's method signature, actually mimics the native indexOf functionality (which is useful in different cases, if the index is what you're truly after).

Important note: Using the tilde shortcut seems to be swathed in controversy, as some vehemently believe that the code is not clear enough and should be avoided at all costs (see the comments on this answer). If you share their sentiment, you should stick to the .indexOf(...) >= 0 solution.

Integers in JavaScript are signed, which means that the left-most bit is reserved as the sign bit; a flag to indicate whether the number is positive or negative, with a 1 being negative.

1 :    00000000000000000000000000000001
2 :    00000000000000000000000000000010
3 :    00000000000000000000000000000011
15:    00000000000000000000000000001111
-1 :   11111111111111111111111111111111
-2 :   11111111111111111111111111111110
-3 :   11111111111111111111111111111101
-15:   11111111111111111111111111110001

Why such weird combinations for the negative numbers? Simple. A negative number is simply the inverse of the positive number + 1; adding the negative number to the positive number should always yield 0.

-1
+1
-15
+15
00000000000000000000000000001111      +15
+  11111111111111111111111111110001      -15
--------------------------------------------
=  00000000000000000000000000000000        0

How do we get those results? By doing regular addition, the way we were taught in school: you start at the right-most column, and you add up all the rows. If the sum is greater than the greatest single-digit number (which in decimal is 9, but in binary is 1) we carry the remainder over to the next column.

Now, as you'll notice, when adding a negative number to its positive number, the right-most column that is not all 0s will always have two 1s, which when added together will result in 2. The binary representation of two being 10, we carry the 1 to the next column, and put a 0 for the result in the first column. All other columns to the left have only one row with a 1, so the 1 carried over from the previous column will again add up to 2, which will then carry over... This process repeats itself till we get to the left-most column, where the 1 to be carried over has nowhere to go, so it overflows and gets lost, and we're left with 0s all across.

This system is called 2's Complement. You can read more about this here:

Now that the crash course in 2's complement is over, you'll notice that -1 is the only number whose binary representation is 1's all across.

Using the ~ bitwise NOT operator, all the bits in a given number are inverted. The only way to get 0 back from inverting all the bits is if we started out with 1's all across.

So, all this was a long-winded way of saying that ~n will only return 0 if n is -1.

Whilst using bitwise operators sure is sexy, is it really better than !== -1 in any conceivable way? Isn't explicit boolean logic more appropriate than implicitly using the falsey-ness of zero?

Nicely techy, but I don't like it. It's not clear at first glance what the code is doing, which makes it unmaintainable. I much prefer "Yuriy Galanter"'s answer.

-1 new programmers see answers like this, think it's a cool and acceptable way of coding, then in 5 years I have to maintain their code and tear my hair out

This idiom is definitely not common in languages like C#, Java, or Python, which are my areas of expertise. And I just asked a few of the local Javascript experts here, and none of them have ever seen it done before; so it is clearly not as common as you claim. It should always be avoided in favor of the much clearer and more common != -1.

-1 due to unnecessary bitfiddling in a language which doesn't really specify a lot about bit representations in the first place. Plus, the bulk of this answer is explaining the bitfiddling. If you have to write 20 paragraphs to explain the hack, does it REALLY save any time?

javascript - How to shorten my conditional statements - Stack Overflow

javascript if-statement
Rectangle 27 235

Short explanation of the ~ tilde shortcut:

Put your values into an array, and check if your item is in the array:

if ([1, 2, 3, 4].includes(test.type)) {
    // Do something
}

If a browser you support doesn't have the Array#includes method, you can use this polyfill.

Update: Since we now have the includes method, there's no point in using the ~ hack anymore. Just keeping this here for people that are interested in knowing how it works and/or have encountered it in other's code.

Instead of checking if the result of indexOf is >= 0, there is a nice little shortcut:

if ( ~[1, 2, 3, 4].indexOf(test.type) ) {
    // Do something
}

How does this work? If an item is found in the array, indexOf returns its index. If the item was not found, it'll return -1. Without getting into too much detail, the ~ is a bitwise NOT operator, which will return 0 only for -1.

I like using the ~ shortcut, since it's more succinct than doing a comparison on the return value. I wish JavaScript would have an in_array function that returns a Boolean directly (similar to PHP), but that's just wishful thinking (Update: it now does. It's called includes. See above). Note that jQuery's inArray, while sharing PHP's method signature, actually mimics the native indexOf functionality (which is useful in different cases, if the index is what you're truly after).

Important note: Using the tilde shortcut seems to be swathed in controversy, as some vehemently believe that the code is not clear enough and should be avoided at all costs (see the comments on this answer). If you share their sentiment, you should stick to the .indexOf(...) >= 0 solution.

Integers in JavaScript are signed, which means that the left-most bit is reserved as the sign bit; a flag to indicate whether the number is positive or negative, with a 1 being negative.

1 :    00000000000000000000000000000001
2 :    00000000000000000000000000000010
3 :    00000000000000000000000000000011
15:    00000000000000000000000000001111
-1 :   11111111111111111111111111111111
-2 :   11111111111111111111111111111110
-3 :   11111111111111111111111111111101
-15:   11111111111111111111111111110001

Why such weird combinations for the negative numbers? Simple. A negative number is simply the inverse of the positive number + 1; adding the negative number to the positive number should always yield 0.

-1
+1
-15
+15
00000000000000000000000000001111      +15
+  11111111111111111111111111110001      -15
--------------------------------------------
=  00000000000000000000000000000000        0

How do we get those results? By doing regular addition, the way we were taught in school: you start at the right-most column, and you add up all the rows. If the sum is greater than the greatest single-digit number (which in decimal is 9, but in binary is 1) we carry the remainder over to the next column.

Now, as you'll notice, when adding a negative number to its positive number, the right-most column that is not all 0s will always have two 1s, which when added together will result in 2. The binary representation of two being 10, we carry the 1 to the next column, and put a 0 for the result in the first column. All other columns to the left have only one row with a 1, so the 1 carried over from the previous column will again add up to 2, which will then carry over... This process repeats itself till we get to the left-most column, where the 1 to be carried over has nowhere to go, so it overflows and gets lost, and we're left with 0s all across.

This system is called 2's Complement. You can read more about this here:

Now that the crash course in 2's complement is over, you'll notice that -1 is the only number whose binary representation is 1's all across.

Using the ~ bitwise NOT operator, all the bits in a given number are inverted. The only way to get 0 back from inverting all the bits is if we started out with 1's all across.

So, all this was a long-winded way of saying that ~n will only return 0 if n is -1.

Whilst using bitwise operators sure is sexy, is it really better than !== -1 in any conceivable way? Isn't explicit boolean logic more appropriate than implicitly using the falsey-ness of zero?

Nicely techy, but I don't like it. It's not clear at first glance what the code is doing, which makes it unmaintainable. I much prefer "Yuriy Galanter"'s answer.

-1 new programmers see answers like this, think it's a cool and acceptable way of coding, then in 5 years I have to maintain their code and tear my hair out

This idiom is definitely not common in languages like C#, Java, or Python, which are my areas of expertise. And I just asked a few of the local Javascript experts here, and none of them have ever seen it done before; so it is clearly not as common as you claim. It should always be avoided in favor of the much clearer and more common != -1.

-1 due to unnecessary bitfiddling in a language which doesn't really specify a lot about bit representations in the first place. Plus, the bulk of this answer is explaining the bitfiddling. If you have to write 20 paragraphs to explain the hack, does it REALLY save any time?

javascript - How to shorten my conditional statements - Stack Overflow

javascript if-statement
Rectangle 27 767

No, but you could return an array containing your values:

Then you can access them like so:

If you want to put "labels" on each of the returned values (easier to maintain), you can return an object:

var newCodes = function() {
    var dCodes = fg.codecsCodes.rs;
    var dCodes2 = fg.codecsCodes2.rs;
    return {
        dCodes: dCodes,
        dCodes2: dCodes2
    };
};
var codes = newCodes();
var dCodes = codes.dCodes;
var dCodes2 = codes.dCodes2;
return {dCodes : dCodes, dCodes2 : dCodes2};

you might even return an object {:dCodes: dCodes, dCodes2: dCodes2} functionally the same but when you reference your returned object you have a bit more readable code as obj.dCodes and obj.dCodes2 vs obj[0] and obj[1]

@alexela Sure you can simply use var dCodes = newCodes().dCodes; var dCodes2 = newCodes().dCodes2 However, you will call the function twice which may be a waste of resources if it is complex.

const { dCodes, dCodes2 } = newCodes();

as other answers said (and comments implied), ES6 brings a few options here. 3 to be exact: (1) object property shorthand return {dCodes, dCodes2} work just the same as @Intelekshual mentioned and (2) using the same function you could simply access them with destructuring arrays [dCodes, dCodes2] = newCodes() or (3) objects ({dCodes, dCodes2} = newCodes()) (no need to use a declaration there @Taylor, though a var would be more fitting for the current Sasha's example).

Return multiple values in JavaScript? - Stack Overflow

javascript
Rectangle 27 18

Ecmascript 6 includes "destructuring assignments" (as kangax mentioned) so in all browsers (not just Firefox) you'll be able to capture an array of values without having to make a named array or object for the sole purpose of capturing them.

//so to capture from this function
function myfunction()
{
 var n=0;var s=1;var w=2;var e=3;
 return [n,s,w,e];
}

//instead of having to make a named array or object like this
var IexistJusttoCapture = new Array();
IexistJusttoCapture = myfunction();
north=IexistJusttoCapture[0];
south=IexistJusttoCapture[1];
west=IexistJusttoCapture[2];
east=IexistJusttoCapture[3];

//you'll be able to just do this
[north, south, west, east] = myfunction();

You can try it out in Firefox already!

Return multiple values in JavaScript? - Stack Overflow

javascript
Rectangle 27 132

(R)eturns the values from array that are not present in the other arrays

_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]

As with any Underscore function, you could also use it in a more object-oriented style:

_([1, 2, 3, 4, 5]).difference([5, 2, 10]);

I think it's a good solution performance-wise, especially as lodash and underscore keep battling for the best implementation. Also, it's IE6-compatible.

underscore, 4k, do a lot, why not :)

Beware, this implementation will not work for arrays of objects. See stackoverflow.com/q/8672383/14731 for more information.

As one of the answers mentions there, it works if it's the same object, but not if two objects have the same properties. I think that's okay as notions of equality vary (e.g. it could also be an "id" attribute in some apps). However, it would be good if you could pass in a comparison test to intersect().

How to get the difference between two arrays in Javascript? - Stack Ov...

javascript arrays array-difference
Rectangle 27 6

One simple way would be to create an array with your expected values.

var years=['Freshman', 'Sophomore', 'Junior', 'Senior' ];
listItems.sort(function(a,b){
    var indexA = $.inArray(  $(a).find('.year').text(), years );
    var indexB = $.inArray( $(b).find('.year').text(), years );
    return ( indexA < indexB) ? -1 : ( indexA > indexB) ? 1 : 0;
});

javascript - How to sort list items using custom sort order in jQuery ...

javascript jquery sorting
Rectangle 27 6

One simple way would be to create an array with your expected values.

var years=['Freshman', 'Sophomore', 'Junior', 'Senior' ];
listItems.sort(function(a,b){
    var indexA = $.inArray(  $(a).find('.year').text(), years );
    var indexB = $.inArray( $(b).find('.year').text(), years );
    return ( indexA < indexB) ? -1 : ( indexA > indexB) ? 1 : 0;
});

javascript - How to sort list items using custom sort order in jQuery ...

javascript jquery sorting