Skip to content

Commit

Permalink
Merge pull request #235 from haskellcamargo/master
Browse files Browse the repository at this point in the history
Array column with similar core implementation
  • Loading branch information
kvz committed Aug 11, 2015
2 parents 94e919c + 51cdcbe commit 4557a75
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions experimental/array/array_column.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
function array_column(array, column_key, index_key) {
// + original by: Marcelo Camargo (https://github.com/haskellcamargo/)
// % note 1: Works only with associative objects, returning an empty
// % note 1: object in case of failure.
// * example 1: var drink, color, power;
// * example 1: array_column([{x: 1, y: 2}, {x: 7, y: 1}], 'x')
// * returns 1: [{0: 1, 1: 7}]
// * example 2: array_column([{x: 1, k: 'a'}, {x: 7, k: 'b'}], 'x')
// * returns 2: [{a: 1, b: 7}]

var result = {},
len = array.length;

index_key = index_key || null;

for (var i = 0; i < len; i++) {
if (!typeof array[i] === "object") {
continue;
} else if (index_key === null && arrya[i].hasOwnProperty(column_key)) {
result[i] = array[i][column_key];
} else if (array[i].hasOwnProperty(index_key)) {
if (column_key === null) {
result[array[i][index_key]] = array[i];
} else if (array[i].hasOwnProperty(column_key)) {
result[array[i][index_key]] = array[i][column_key];
}
}
}
return result;
}

0 comments on commit 4557a75

Please sign in to comment.