Home > Enterprise >  How To get the values of object sorted with keys in distinct arrays?
How To get the values of object sorted with keys in distinct arrays?

Time:08-21

Given an array of arrays, I want to get the averages of each subarray, and then output which subarrays have the same average. The output will not repeat the subarrays, but just the indices where they occur in the input array.

So for this input:

[
  [3, 3, 4, 2], // index 0: average = 3
  [4, 4],       // index 1: average = 4
  [4, 0, 3, 3], // index 2: average = 2.5
  [2, 3],       // index 3: average = 2.5
  [3, 3, 3],    // index 4: average = 3
];

The expected output is:

[[0, 4], [1], [2, 3]]

...because the subarrays at indices 0 and 4 have the same average, while the subarray at index 1 has an average that is not shared by another subarray, and finally the subarrays at indices 2 and 3 have the same average.

I completed the function as we see below, and the averages are calculated correctly, but I can't get the values of the object sorted with keys in distinct arrays...

function solution(a) {
  let b = [];
  let entier = {};
  a.filter((elt, cle) => {
    let s = a[cle].reduce((prevalue, curvalue) => prevalue   curvalue, 0);
    b[cle] = s / a[cle].length;
    //console.log(s/a[cle].length)
    entier[cle] = s / a[cle].length;
  });
  console.log(entier);
  let arrNew = Object.entries(entier);
  console.log(arrNew);
}

let a = [
  [3, 3, 4, 2],
  [4, 4],
  [4, 0, 3, 3],
  [2, 3],
  [3, 3, 3],
];

solution(a); // [[0, 4], [1], [2, 3]]

How can I make my code work?

CodePudding user response:

With this:

entier[cle] = s / a[cle].length;

...you are assigning the average as a value associated with the current index as the key. But you need the opposite. You'll want to group by the average, so that must be the key, and the index must be the value (but as an array).

So change that to:

(entier["x"   (s / a[cle].length)] ??= []).push(cle);

The "x" is to ensure that the key is not an integer as then different rules apply for the ordering of that key in the object. By prepending this "x", we ensure that keys are ordered in the order they are created.

The ??= assignment ensures that the property is initialised as an array when it didn't exist yet.

The second correction is here: Object.entries should be Object.values as you are no longer interested in those "x" keys.

function solution(a) {
  let entier = {};
  a.filter((elt, cle) => {
    let s = a[cle].reduce((prevalue, curvalue) => prevalue   curvalue, 0);
    (entier["x"   (s / a[cle].length)] ??= []).push(cle);
  });
  let arrNew = Object.values(entier);
  console.log(arrNew);
}

let a = [
  [3, 3, 4, 2], // 0: 3
  [4, 4],       // 1: 4
  [4, 0, 3, 3], // 2: 2.5
  [2, 3],       // 3: 2.5
  [3, 3, 3],    // 4: 3
];

solution(a); // [[0, 4], [1], [2, 3]]

  • Related