함수 unique_array_by_value()


1 개요[ | ]

함수 unique_array_by_value()

2 JavaScript[ | ]

JavaScript
Copy
function uniqueArrayByValue(rows, column) {
  var arr = [];
  for( var i in rows ) {
    row = rows[i];
    if( arr.hasOwnProperty(row[column])) continue;
    arr[row[column]] = row;
  }
  return arr;
}
var revisions = [
	{user:'A',timestamp:'2018-01-15T10:55:04Z'},
	{user:'B',timestamp:'2017-07-14T17:08:00Z'},
	{user:'C',timestamp:'2016-12-27T05:48:18Z'},
	{user:'B',timestamp:'2016-03-29T05:00:16Z'},
	{user:'A',timestamp:'2015-09-28T08:06:25Z'}
];
console.log( uniqueArrayByValue(revisions, 'user') );
// [
// A: {user: "A", timestamp: "2018-01-15T10:55:04Z"}
// B: {user: "B", timestamp: "2017-07-14T17:08:00Z"}
// C: {user: "C", timestamp: "2016-12-27T05:48:18Z"}
// ]

3 PHP[ | ]

PHP
Copy
function unique_array_by_value($rows, $column) {
	$arr = [];
	foreach( $rows as $row ) {
		if( array_key_exists($row[$column],$arr)) continue;
		$arr[$row[$column]] = $row;
	}
	return array_values( $arr );
}
$revisions = [
['user'=>'A','timestamp'=>'2018-01-15T10:55:04Z'],
['user'=>'B','timestamp'=>'2017-07-14T17:08:00Z'],
['user'=>'C','timestamp'=>'2016-12-27T05:48:18Z'],
['user'=>'B','timestamp'=>'2016-03-29T05:00:16Z'],
['user'=>'A','timestamp'=>'2015-09-28T08:06:25Z'],
];

print_r( unique_array_by_value($revisions, 'user') );
# Array
# (
#     [0] => Array
#         (
#             [user] => A
#             [timestamp] => 2018-01-15T10:55:04Z
#         )
#     [1] => Array
#         (
#             [user] => B
#             [timestamp] => 2017-07-14T17:08:00Z
#         )
#     [2] => Array
#         (
#             [user] => C
#             [timestamp] => 2016-12-27T05:48:18Z
#         )
# )

4 같이 보기[ | ]