Fork me on GitHub

Learn how to do it in JavaScript. Explore boundaries porting languages. Enjoy functions that turn out to be useful.

JavaScript array_flip function

A JavaScript equivalent of PHP’s array_flip

array/array_flip.js raw on github
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function array_flip (trans) {
  // http://kevin.vanzonneveld.net
  // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +      improved by: Pier Paolo Ramon (http://www.mastersoup.com/)
  // +      improved by: Brett Zamir (http://brett-zamir.me)
  // *     example 1: array_flip( {a: 1, b: 1, c: 2} );
  // *     returns 1: {1: 'b', 2: 'c'}
  // *     example 2: ini_set('phpjs.return_phpjs_arrays', 'on');
  // *     example 2: array_flip(array({a: 0}, {b: 1}, {c: 2}))[1];
  // *     returns 2: 'b'

  var key, tmp_ar = {};

  if (trans && typeof trans=== 'object' && trans.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array
    return trans.flip();
  }

  for (key in trans) {
    if (!trans.hasOwnProperty(key)) {continue;}
    tmp_ar[trans[key]] = key;
  }

  return tmp_ar;
}

Example 1

This code

example
1
array_flip( {a: 1, b: 1, c: 2} );

Should return

returns
1
{1: 'b', 2: 'c'}

Example 2

This code

example
1
2
ini_set('phpjs.return_phpjs_arrays', 'on');
array_flip(array({a: 0}, {b: 1}, {c: 2}))[1];

Should return

returns
1
'b'

Other PHP functions in the array extension

Legacy comments

These were imported from our old site. Please use disqus below for new comments

Brett Zamir on 2011-07-20 03:47:32
@Pier Paolo Ramon: Good catch! Thanks–fixed in Git… (This function as with many others still needs to support reliably ordered associative arrays–see PHPJS_Array() in array().)
Pier Paolo Ramon on 2011-07-15 16:45:51
You should check if it’s a property of the object, with hasOwnProperty.

for (key in trans) {
  if (!trans.hasOwnProperty(key)) continue;
  tmp_ar[trans[key]] = key;
}


Comments