bmallred

jump to main content
Dark Mode

Javascript

Find duplicates in array

const duplicates = (items, fn) => {
    const dupes = [];

    const unique = items.reduce((accumulator, current) => {
        if (fn(accumulator, current)) {
            // If this duplicate has not already been recorded then we need to remember it.
            if (!fn(dupes, current)) {
                dupes.push(current);
            }

            return accumulator;
        }

        // Not a duplicate according the check().
        accumulator.push(current);
        return accumulator;
    }, []);

    return dupes;
};

Sort date

// descending
[].sort((a, b) => new Date(b.createdDate) - new Date(a.createDate))
// ascending
[].sort((a, b) => new Date(a.createdDate) - new Date(b.createDate))

Group by

const groupBy = (items, getKey) => {
  return items.reduce((accumulator, item) => {
    const key = getKey(item);
    if (accumulator[key]) {
      accumulator[key].push(item);
    } else {
      accumulator[key] = [item];
    }
    return accumulator;
  }, {});
};

Padding

#+BEGIN_SRC javascript /**

  • pad
  • @summary Pad a value to the left or right with a token.
  • @param {String} value
  • @param {Integer} length
  • @param {String} char
  • @param {Boolean} left
  • @return {String}

*/ const pad = (value, length, char = ' ', left = true) => { // Create the padding let padding = ''; for (let i = 0; i < length; i++) { padding = `\({padding}\){char}`; }

// Convert the value to a string const sval = `${value || ''}`;

// Perform the directional padding if (!left) { return sval + padding.substring(0, padding.length - sval.length); } return padding.substring(0, padding.length - sval.length) + sval; }; #+END_SRC javascript