Skip to content

Instantly share code, notes, and snippets.

@behnamazimi
Forked from rauschma/partition.js
Created September 7, 2020 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save behnamazimi/1d2c35f4649fa04e7c89dacc2bed73c4 to your computer and use it in GitHub Desktop.
Save behnamazimi/1d2c35f4649fa04e7c89dacc2bed73c4 to your computer and use it in GitHub Desktop.
function partition(inputArray, callback) {
const result = {};
for (const [indexOfValue, value] of inputArray.entries()) {
const propertyKey = callback(value, indexOfValue);
if (propertyKey === null || propertyKey === '') {
continue;
}
if (!{}.hasOwnProperty.call(result, propertyKey)) {
result[propertyKey] = [];
}
result[propertyKey].push(value);
}
return result;
}
const arr = [1, -5, 4, 5, -2]
const {negative, nonNegative} = partition(arr,
elem => elem < 0 ? 'negative' : 'nonNegative');
console.log(negative);
// [ -5, -2 ]
console.log(nonNegative);
// [ 1, 4, 5 ]
const input = [
{name: 'John', isLocal: true},
{name: 'Jane', isLocal: false},
{name: 'Charlie', isLocal: true}
];
const {local, global} = partition(input,
(elem) => elem.isLocal ? 'local' : 'global');
console.log(local);
// [ { name: 'John', isLocal: true }, { name: 'Charlie', isLocal: true } ]
console.log(global);
// [ { name: 'Jane', isLocal: false } ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment