Home > OS >  Count Value of multi dimensional array in Javascript
Count Value of multi dimensional array in Javascript

Time:01-09

var sortedArr = [["Paul",     "1355"],
  ["Jennifer", "1910"],
  ["John",      "835"],
  ["John",      "830"],
  ["Paul",     "1315"],
  ["John",     "1615"],
  ["John",     "1640"],
  ["Paul",     "1405"],
  ["John",      "855"],
  ["John",      "930"],
  ["John",      "915"],
  ["John",      "730"],
  ["John",      "940"],
  ["Jennifer", "1335"],
  ["Jennifer",  "730"],
  ["John",     "1630"],
  ["Jennifer",    "5"]
];

I am trying to find the total number of counts for each key, For example, Paul appears three times so Paul should count 3 times.

and then want to write all the values for it. For example for Paul value should be 1355 1315 1405

It should be Like Paul 1355, 1315, 1405

I try something, but I get some issues, the issue are more about logic. Can someone please guide me?


  count = 1;
 var test;

//sortedArr = arr.sort();

for (var i = 0; i < sortedArr.length; i = i   count) {

  count = 1;
  test = [];
  test.push(sortedArr[i][1]);
 
  for (var j = i   1; j < sortedArr.length; j  ) {
  
    if (sortedArr[i][0] === sortedArr[j][0])
    {
      count  ;
     // 
       test.push(sortedArr[j][1]);
       
  }
  }
  document.write(sortedArr[i][0]   test  " = "   count   "<br>");
 
}

Output (wrong)

Paul1355,1315,1405 = 3
John830,1615,1640,855,930,915,730,940,1630 = 9
John940,1630 = 2
Jennifer730,5 = 2
Jennifer5 = 1

Output should be

Paul1355,1315,1405 = 3
John835, 830,1615,1640,855,930,915,730,940,1630 = 10
Jennifer1910, 1335, 730,5 = 4

Can someone tell me the issue in my code?

CodePudding user response:

Your sortedArr isn't sorted, so the results are erratic. In JavaScript, sort() modifies the array directly, so you only need to add

sortedArr.sort();

and your code works.

var sortedArr = [["Paul",     "1355"],
  ["Jennifer", "1910"],
  ["John",      "835"],
  ["John",      "830"],
  ["Paul",     "1315"],
  ["John",     "1615"],
  ["John",     "1640"],
  ["Paul",     "1405"],
  ["John",      "855"],
  ["John",      "930"],
  ["John",      "915"],
  ["John",      "730"],
  ["John",      "940"],
  ["Jennifer", "1335"],
  ["Jennifer",  "730"],
  ["John",     "1630"],
  ["Jennifer",    "5"]
];

 count = 1;
 var test;

sortedArr.sort();

for (var i = 0; i < sortedArr.length; i = i   count) {
  count = 1;
  test = [];
  test.push(sortedArr[i][1]);
 
  for (var j = i   1; j < sortedArr.length; j  ) {    
    if (sortedArr[i][0] === sortedArr[j][0]) {
      count  ; 
      test.push(sortedArr[j][1]);     
      }
  }
  document.write(sortedArr[i][0]   test  " = "   count   "<br>");
}

CodePudding user response:

Respecting and understanding the way you are trying to solve the problem, your logic is correct except that it needs a sorted list because your implementation skips consecutive entries with similar names with count it has to be sorted for that. So sorting the array before you check the values will give you the proper results:

sortedArr.sort((a, b) => b.toString().localeCompare(a.toString()));

Note I have sorted the array in descending order to match your output. If you just call sortedArr.sort() it should also give the correct results but in reverse output order.

CodePudding user response:

You can first organize the data and then print it to the document.

  1. First you can iterate over the array using Array.prototype.reduce and convert it into object where each field will be <perosn_name> : <array_of_values>.

  2. Then again iterate to print in the form of <name> = <comma separated values> = <count> of the values (using Object.entries and Array.prototype.forEach)

Try like below

var sortedArr = [
  ["Paul", "1355"],
  ["Jennifer", "1910"],
  ["John", "835"],
  ["John", "830"],
  ["Paul", "1315"],
  ["John", "1615"],
  ["John", "1640"],
  ["Paul", "1405"],
  ["John", "855"],
  ["John", "930"],
  ["John", "915"],
  ["John", "730"],
  ["John", "940"],
  ["Jennifer", "1335"],
  ["Jennifer", "730"],
  ["John", "1630"],
  ["Jennifer", "5"],
];

// convert the data into the form described
const output = sortedArr.reduce((prevValue, [name, value]) => {
  prevValue[name] ? prevValue[name].push(value) : (prevValue[name] = [value]);
  return prevValue;
}, {});

// write to the document
Object.entries(output).forEach(([name, arr]) => {
  document.write(`${name} = ${arr.join(",")} = ${arr.length}<br>`);
})

NOTE: Always try to use the built-in Array prototype functions. Most of the time you can use them and easy to read your code.

CodePudding user response:

Put all of them in a object, and you can get what you want.

const result = sortedArr.reduce((acc, curr) => {
  const [name, number] = curr
  if (acc[name]) {
    acc[name].push(number)
  } else {
    acc[name] = [number]
  }
  return acc
},{})

// you can use result["Paul"] to get the count of Paul
// don't need to add count variable

CodePudding user response:

You can use Map for this use-case

let map = new Map();

sortedArr.forEach((item)=>{
  let [key, value] = item;
  if(!map.has(key)) {
    map.set(key, [])
  }
  map.get(key).push(value)
})


for(let [key, value] of map.entries()) {
  console.log(`${key} ${value} = ${value.length}`);
}

Output is

Paul 1355,1315,1405 = 3
Jennifer 1910,1335,730,5 = 4
John 835,830,1615,1640,855,930,915,730,940,1630 = 10
  •  Tags:  
  • Related