0

I am having multiple objects in an array i want to make the element in each object same

var objectArray = [obj1,obj2,obj3.........]

obj1 ={
2002-Edad 15 a 64 años: 0.1854095,
2003-Edad 15 a 64 años: 0.1531632,
2005-Edad 15 a 64 años: 0.1887739,
2006-Edad 15 a 64 años: 0.1754043,
2007-Edad 15 a 64 años: 0.2038664,
2008-Edad 15 a 64 años: 0.2270297,
2009-Edad 15 a 64 años: 0.211827,
2011-Edad 15 a 64 años: 0.2396887,
2012-Edad 15 a 64 años: 0.2618066,
2013-Edad 15 a 64 años: 0.2677819,
var_descripcion: "Asalariados con contrato a término fijo (en %)"}

obj2 ={
2002-Edad 15 a 64 años: 0.1854095,
2003-Edad 15 a 64 años: 0.1531632,
2005-Edad 15 a 64 años: 0.1887739,
2006-Edad 15 a 64 años: 0.1754043,
2007-Edad 15 a 64 años: 0.2038664,
2011-Edad 15 a 64 años: 0.2396887,
2012-Edad 15 a 64 años: 0.2618066,
2013-Edad 15 a 64 años: 0.2677819,
var_descripcion: "Asalariados con contrato a término fijo (en %)"}

I want to compare this arrays and insert the missing value in second arrays ie,

2008-Edad 15 a 64 años: 0.2270297 & 2009-Edad 15 a 64 años: 0.211827 

but value as 0

In this way I want to make all the objects in array similar

Please help;

2 Answers 2

1

Here is an example of how you could do that. You will find that after having executed normalizeArray on the test array that the second object in the array will have the "second" property initialized to 0. Here's a fiddle of it working.

function mergeObject(from, to) {
  for(var prop in from) {
    if (typeof(to[prop]) === 'undefined') {
      to[prop] = 0;
    }
  }

  return to;
}

function normalizeArray(arr) {
  var schema = {};
  for(var i = 0; i < arr.length; i++) {
    schema = mergeObject(arr[i], schema);
  }

  for(var i = 0; i < arr.length; i++) {
    arr[i] = mergeObject(schema, arr[i]);
  }
}

var test1 = {
  first: 1,
  second: 2,
  third: 3
}

var test2 = {
  first: 1,
  third: 3
}

var testArray = [test1, test2];

normalizeArray(testArray);
Sign up to request clarification or add additional context in comments.

Comments

0

Simply compare the arrays;

            var array1 = [1,2,3,4,5],
                array2 = [5,4,3,2,1],
                array3 = [1,2,,6,7,8];

            function compareArrays(arr1, arr2) {
                return $(arr1).not(arr2).length == 0 && $(arr2).not(arr1).length == 0
            };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.