2

I'm wondering if JavaScript has a way of doing something like

var x = { 'a' : 4, 'b' : -1 }; 
var y = { 'c' : 0 }; 
var z = x + y; // { 'a' : 4, 'b' : -1, 'c' : 0 }

outside of rolling my own function or importing a library.

The reason I'm wondering is because I want to use reduce to get the unique values in an array, something like

var arr = [1, 5, 1, 10, 239, -1, 1, 5]; 
var unique = Object.keys(arr.reduce((prev,cur) => ???, {})).map(key => key); // [1, 5, 10, 239, -1];

where I don't know what to put for the ??? above.

Ms. Corlib
  • 4,993
  • 4
  • 12
  • 19
  • `var z = Object.assign(x, y);` is the standard, but not all browsers support it yet. – Sebastian Simon Jun 23 '16 at 22:02
  • @BerkayYaylaci Creates a new array by adding the values from one array to the end of another array. It doesn't add missing properties to different objects. – Mike Cluck Jun 23 '16 at 22:02
  • 1
    @Xufox That modifies `x`. You would want: `var z = Object.assign({}, x, y);`. – Paul Jun 23 '16 at 22:09
  • 1
    @Xufox There is also a [straightforward polyfill](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill) which makes it work in browsers that don't support it yet. – Paul Jun 23 '16 at 22:11

1 Answers1

4

For your first example, it's Object.assign (which is new in ES2015, but it can be polyfilled for older JavaScript engines):

var x = { 'a' : 4, 'b' : -1 }; 
var y = { 'c' : 0 }; 
var z = Object.assign({}, x, y);
console.log(z); // { 'a' : 4, 'b' : -1, 'c' : 0 }

The reason I'm wondering is because I want to use reduce to get the unique values in an array, something like

It doesn't really come into that, there's either the repeatedly-search-the-array approach (reduce can be used for it, but it doesn't buy you much over forEach):

var arr = [1, 5, 1, 10, 239, -1, 1, 5]; 
var unique = arr.reduce(function(result, entry) {
  if (result.indexOf(entry) == -1) {
    result.push(entry);
  }
  return result;
}, []);
console.log(unique);

...or the map-to-object-properties-and-then-take-the-property-names-at-the-end approach, where reduce again doesn't really buy you much:

var arr = [1, 5, 1, 10, 239, -1, 1, 5]; 
var unique = Object.keys(arr.reduce(function(result, entry) {
  result[entry] = true;
  return result;
}, {}));
console.log(unique);

In the latter, you also end up with strings rather than numbers. Of course, you could turn them back into numbers by adding .map(function(entry) { return +entry; }) to the end.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875