-1

I have created a matrix like:

u = Array.from({ length: 100}, (v, i) => []);
console.log(u)

Then, after running the code and filling the matrix. I wanted to get the index of the minimum element in particular row.so the result should be either 0 or 1.

act[i] = u.indexOf(Math.min.apply(null,u[i]));

However, I get -1 sometimes. I read that negative number means the element does not exist in the array. In my case it always exist.

to check that it exist I used console.log() and it does always exist but for some reason it still return -1 as an index.

Alex L
  • 4,168
  • 1
  • 9
  • 24
nora
  • 27
  • 2
  • you have no values in the inner arrays. and even if so, you have to search for the same object reference. – Nina Scholz Jun 09 '20 at 07:23
  • I think I understand what you want to do (see my answer) but in general, you should include enough code so that we don't need to guess. (for example, include the code to "fill the Matrix") https://stackoverflow.com/help/minimal-reproducible-example – Alex L Jun 09 '20 at 09:03
  • 1
    Thank you all. I think this solved the problem act[i] = u[i].indexOf(Math.min.apply(null,u[i])); – nora Jun 10 '20 at 11:23

1 Answers1

0

You could do it like this:

Loop over your Matrix, find the minimum of that row by passing in the row into the Math.min() function - using the spread syntax const min_val = Math.min(...u[row]); (to "unpack" the array items into the function arguments). Put this min value into your act array with act[row] = min_val; OR put the index of this min value into your array with act[row] = u[row].indexOf(min_val); (or you could do both).

If you don't need all min values/indexes (and just need a given row on demand) you can just use the function at the bottom.

const ROWS = 100;
const COLS = 5;

const u = Array.from({ length: ROWS}, (v, i) => []);

//let's fill the Matrix:
for (let row = 0; row < u.length; row++){
  for (let col = 0; col < COLS; col++){
    u[row].push(Math.random());
  }  
}

console.log(u)

//Create an array of all min values/indexes:
const act = Array(u.length);

for (let row = 0; row < u.length; row++){
  const min_val = Math.min(...u[row]);
  //put min value in:
  //act[row] = min_val;
  
  //or put min value index in:
  act[row] = u[row].indexOf(min_val);
  
  //or you could do both:
  //act[row] = [ min_val, u[row].indexOf(min_val) ];
}

console.log(act)

//if you just want to get any min index of any row on the fly use this function:
function getMinIndexAtRow(inputArr, row){
  const min_val = Math.min(...inputArr[row]);
  return u[row].indexOf(min_val);
}

//use it like this:
console.log(getMinIndexAtRow(u, 0));
Alex L
  • 4,168
  • 1
  • 9
  • 24