1

Lets say I have several objects. These objects have four properties each, containing simple integers. I want to create another object with the highest values for each property, so its a chimeric object. I don't want it to change the originals when I manipulate it and vice versa.

Whats the way to do this in javascript? A simple assignment would create a reference, but I need a duplicate.

PS: Pure JS please, no libraries.

1
  • "with the highest values" would not be a clone of anything? Commented Dec 10, 2014 at 1:20

2 Answers 2

1

It sounds like you are trying to do something like this.

Updated as per comments

// Source objects.
var objects = [
  { x: 3, y: 4, z: 36 },
  { x: 9, y: 5, z: 9 },
  { x: 1, y: 3, z: 100 },
  { x: 7, y: 0, z: 18 },
];

// Result object.
var result = {
    x: objects[0].x,
    y: objects[0].y,
    z: objects[0].z
};

// Set the maximum value for each property. 
for(var i = 1; i < objects.length; i++){
  result.x = Math.max(result.x, objects[i].x);
  result.y = Math.max(result.y, objects[i].y); 
  result.z = Math.max(result.z, objects[i].z); 
}
Sign up to request clarification or add additional context in comments.

4 Comments

result will be Object {x: 9, y: 5, z: 100}
@mido22 - no it doesn't. Math.max() works just fine for negative values too.
@jfriend00 @sam , think about it, if all the values in objects are negative, the result would be 0,0,0 (instead of least negative value) which is wrong
i guess, initializing the result with the vaules of first element in objects would resolve it.
0

Ok, found the glitch. I initiated the result object by simply copying one of the source objects, generating a completely new object would fix it. Thanks!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.