Zorgg Zorgg - 1 year ago 56
Javascript Question

Array organization

I've been working with arrays and what I want is to create a formula that will allow me to loop over an array that contains objects and take keys with different values and turn them into a multi-dimensional array (I need to keep the order of the keys). I'm already getting this array but now I need to add ['n/a', '--'] on every position where the strings are not the same, like this:

var all = [
{banana: 1, rose: 2, mouse: 9, apple: 5, ana: 4, carl: 'truck'},
{banana: 1, rock: 58, car: 19, apple: 5, cheese: 3, carl: 'blue'},
{banana: 1, cheese: 2, red: 14, clue: 89, apple: 5, ana: 8}

//expected to get:
var new-arr = [ [["ana", 4], ["n/a", "--"], ["carl", "truck"]],
["n/a", "--"], ["cheese", 3], ["carl", "blue"]],
[["ana", 8], ["cheese", 2], ["n/a", "--"]] ];

So that at the end I cna create a list like this


  • ana: 4

  • n/a: --

  • carl: truck


  • n/a: --

  • cheese: 3

  • carl: blue


  • ana: 8

  • cheese: 2

  • n/a: --

The code is here

Did I do something wrong? Is there any way I can do it all in one function?

Answer Source

Your bug is not shown in the question, but it is in the fiddle, in this portion:

$('.lol').each(function (i, elm) {
similar_keys[i].forEach(function(spec, j){
  similar_keys[j].forEach(function (spec1, j1){
    if(spec[0] != spec1[0] && j != j1){
      similar_keys[i].push(['n/a', '--']);

it doesn't make any sense to iterate through similar_keys[j] on the 3rd loop. j is an index of the inner array. This code just makes no sense. You even rely on having the same number of elements in the DOM and objects in your data.

I can only guess at what you are trying to accomplish, but I would modify your original algorithm instead. Maybe this:

function similars(arr) {
var similar_keys = [];
for (var i = 0; i < arr.length; i++) {
  var tempArr = [];
  for (var key in arr[i]) {
    var found = false;
    var count = 0;
    var index = 0;
    for (var j = 0; j < arr.length; j++) {
      if (arr[j].hasOwnProperty(key)) {
    if (i !== j && arr[j][key] === arr[i][key]) {
     found = true;
    if (!found && count > 1) {
      tempArr.push([key, arr[i][key]]);
    else if (count > 1) {
      tempArr.push(["N/A", arr[i][key]]);
return similar_keys;


EDIT: Still not sure what you are looking for. What I think you need to do:

1) Sort each of the rows in similar_keys by the first element 2) Compare first element of each row, and insert the N/A entry to the row with the lowest sort order. 3) continue through each column, inserting as necessary.

i will try to modify your fiddle to demonstrate

EDIT: this should work. https://jsbin.com/nesiqogebo/edit?js,console,output

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download