Skip to content

Instantly share code, notes, and snippets.

@hollygood
Last active May 17, 2021 01:54
Show Gist options
  • Save hollygood/5644d3c235b6481ae0c4850e9ba17e21 to your computer and use it in GitHub Desktop.
Save hollygood/5644d3c235b6481ae0c4850e9ba17e21 to your computer and use it in GitHub Desktop.
JS Arrays || Objects Tricks

Some Common JS Tricks

Toggle Sorting function

// Normal way
if ( this.orderBy ) {
  results = this.order === 'asc' ? 
  results[0].sort( (a, b) => ( 
    a[ this.orderBy ] > b[ this.orderBy ] ) ? 1 : -1 ):
  results[0].sort( (a, b) => ( 
    a[ this.orderBy ] < b[ this.orderBy ] ) ? 1 : -1 );
}

// Better way
const inversionFactor = this.order === 'asc' ? 1 : -1;
results = results[0].sort( (a, b) =>
    a[ this.orderBy ] < b[ this.orderBy ] : -1 * inversionFactor : 1 * inversionFactor
);

// this is a reusable function and can go outside of other functions
const compareBy = (prop, invert) => (a, b) => {
    if (a[prop] === b[prop]) { return 0; } 
    return (a[prop] < b[prop] ? -1 : 1) * (invert ? -1 : 1);
};

results = results[0].sort(compareBy(this.orderBy, this.order === 'desc'));

Sorting an array by multiple properties

export enum type {
    high,
    medium,
    low
}
const array;
array.sort((a, b) =>
    type[a.type] - type[b.type] ||
    a.desc - b.desc ||
    a.time.localeCompare(b.time)
);

Compare two arrays of objects and remove the common objects or take common objects

const data = [{
        id: "1",
        name: "abc"
    },
    {
        id: "2",
        name: "cde"
    },
    {
        id: "3",
        name: "efg"
    },
    {
        id: "4",
        name: "hij"
    },
    {
        id: "5",
        name: "klm"
    }
];
const data1 = [{
        code: "23",
        id: "1",
        name: "abc"
    },
    {
        code: "45",
        id: "2",
        name: "cde"
    }
];
const result = data.filter(({
    id
}) => !data1.some(val => val.id === id));
console.log(result);

Get items from an array that equal to the values in an array?

let arr = [{'id': "1"}, {'id': "8"}]
let ids =["1","2","3","4"];
var findIndex = arr.filter(f => ids.indexOf(f.id)!=-1)
// or
var includes = arr.filter(f => ids.includes(f.id))

Convert an array to an array of objects, selecting the key from another array

const propertyName = ['id', 'createid', 'sentid'];
const value = [
    ['1', '2', '3'],
    ['3', '4', '5'],
    ['6', '7', '8'],
];
const dataObjs = value.map(a =>
    Object.fromEntries(a.map((e, i) => [propertyName[i], e]))
);
console.log(dataObjs);

Merge two Arrays without duplicate items

// Lodash union
_.union([1, 2, 3], [1, 2, 4 ,6])

// Filter and concat 
let a = [56, 43, 3], b = [11, 43, 56, 12]
let c = a.concat(b)
let d = c.filter((val, pos) => c.indexOf(val) === pos)

// Set
[...new Set([...array1 ,...array2])];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment