JavaScript Array Functions

From Q
(Redirected from EqualArraysOfIntegers)
Jump to navigation Jump to search

This page contains functions to manipulate or create JavaScript arrays.

To make these functions available when writing a QScript or Rule see JavaScript Reference.

arrayHasDuplicateElements(array)

Returns true if the input array contains any of its elements more than once.

uniqueElementsInArray(array)

Returns an array containing the unique elements of the input array (that is, it removes any duplicate elements).

arraySum(array)

Returns the sum of the elements in the input array.

getElementsOfArrayBySelectedIndices(array, indices)

Returns the elements of the input array at the indices specified in the input array indices. For example

getElementsOfArrayBySelectedIndices(["a","b","c","d"], [0,3])

returns the array

["a","d"]

equalArraysOfIntegers(a1, a2)

Returns true if the two input arrays a1 and a2 contain the same elements in the same order.

rep(x, k)

Returns an array which that replicates the elements of x a total of k number of times; this function requires IsArray. There are three different ways that it can be used:

  • rep("One",3) will create ["One","One","One"] and, similarly, Rep(1,3) will create [1,1,1].
  • rep([1,2],3) will replicate the entire elements of the array three times as [1,2,1,2,1,2].
  • rep([1,2],[3,4]) will return [1,1,1,2,2,2,2].

labelAsArray(input_string, delimiters, max_length)

This function splits up the input_string according to the array of specified delimiters and returns an array of the resulting substrings. Only the first max_length elements are returned.

enumerateDuplicatesInStringArray(string_array, before_symbol, after_symbol)

Returns a new copy of string_array where duplicate strings have been enumerated using the before_symbol and after_symbol. For example, if the input symbols are '(' and ')' and the input string_array is ["dog", "cat", "dog"] then the resulting array will be ["dog (1)", "cat", "dog (2)"].

splitArrayIntoApplicableAndNotApplicable(array, my_function)

Split an array into two arrays based on whether or not each element of the array returns true or false when passed to my_function.

Returns an object with two properties:

  • applicable - those elements of the input array that returned true.
  • notApplicable - those remaining elements which returned false.

Source Code

includeWeb('JavaScript Utilities');

// checking to see if an array has duplicates
function arrayHasDuplicateElements(array){
    return array.length != uniqueElementsInArray(array).length;
}

// an array of unique values from http://dreaminginjavascript.wordpress.com/2008/08/22/eliminating-duplicates/
function uniqueElementsInArray(array){
    var i,
        len=array.length,
        out=[],
        obj={};

    for (i=0;i<len;i++) {
        obj[array[i]]=0;
    }
    for (i in obj) {
        out.push(i);
    }
    return out;
}

// Add up all of the elements of an array
function arraySum(array) {
    return array.reduce(function(a,b) { return a + b; }, 0);
}

// Return a new array containing the elements of array at corresponding
// to indices.
function getElementsOfArrayBySelectedIndices(array, indices) {
    var new_array = [];
    var num_indices = indices.length;
    for (var j = 0; j < num_indices; j++)
        new_array.push(array[indices[j]]);
    return new_array;
}

function equalArraysOfIntegers(a1, a2) {
    if (!Array.isArray(a1) || !Array.isArray(a2))
        return false;
    if (a1.length != a2.length)
        return false;

    var num_elements = a1.length;
    for (var j = 0; j < num_elements; j++)
        if (a1[j] != a2[j])
            return false;

    return true;
}

// Returns an array which that replicates the elements of x a total of k number of times
function rep(x, k) {
    var n = x.length;
    if (!isArray(x))
        return rep([x],k);
    if (!isArray(k)) {
        var result = new Array(n * k);
        for (var j = 0; j < k; j++)
            for (var i = 0; i < n; i++)
                result[i + j * n] = x[i];
        return result;
    }
    if (k.length != x.length)
        alert("If x and k are both arrays in 'rep', then they need to have the same length.");
        var result = new Array();
        for (var j = 0; j < n; j++)
            for (var i = 0; i < k[j]; i++)
                result.push(x[j]);
        return result;
}

//a function for turning a string into an array
function labelAsArray(input_string, delimiters, max_length) { 
    var counter = 0;
    var array = []; 
    while (counter++ <= delimiters.length && array.length < max_length) //stops when an array of 2 or more entries is found
        array = input_string.split(delimiters[counter-1]); //splitting into an array
    return array;
}

// Returns a new copy of string_array where duplicate strings have been enumerated
// using the befor_symbol and after_symbol
function enumerateDuplicatesInStringArray(string_array, before_symbol, after_symbol) {
    var sorted_array = string_array.slice(0).sort();
    var enumerated = string_array.slice(0);
    var duplicates = [];
    for (var j = 0; j < sorted_array.length - 1; j++)
        if (sorted_array[j+1] == sorted_array[j])
            duplicates.push(sorted_array[j]);
    duplicates = uniqueElementsInArray(duplicates);
    duplicates.forEach(function(dup) {
        var count = 0;
        enumerated = enumerated.map(function(string) {
            if (string == dup) {
                count++;
                return string + ' ' + before_symbol + count + after_symbol;
            } else
                return string;
        });
    });
    return enumerated;
} 

// Split an array up according to whether my_function returns true or false
// for each element.
function splitArrayIntoApplicableAndNotApplicable(array, my_function) {
    var applicable = [];
    var not_applicable = [];
    array.forEach(function (x) {
        if (my_function(x))
            applicable.push(x);
        else
            not_applicable.push(x);
    });
    return {applicable: applicable, notApplicable: not_applicable};
}

function allEqual(arr) {
    return arr.every(a => a === arr[0])
}

// Functions to compute array maximum and minimum
// without using an 'apply' call which can hit a 
// stack overflow for large arrays.
function arrayMin(arr) {
  return arr.reduce(function (p, v) {
    return ( p < v ? p : v );
  });
}

function arrayMax(arr) {
  return arr.reduce(function (p, v) {
    return ( p > v ? p : v );
  });
}

See Also