Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

min - finding the minimim value in an array and its index - total beginner so any assistance would be hugely appreciated

Working on a web development project and have managed to find my self tasked with implementing a simple JavaScript function. However I have little to no skill in the area so am trying to work my way through the problem:

I have to lists of numbers and have managed to sum them using the code:


function myFunction2() {
  Array.prototype.SumArray = function (arr) {
    var arraytotal = [];
    if (arr != null && this.length == arr.length) {
        for (var i = 0; i < arr.length; i++) {
            arraytotal.push(this[i] + arr[i]);
        }
    }

    return arraytotal;
  
}

var array1 = [1, 9, 10, 6];
var array2 = [9, 6, 7, 8];
var arraytotal = array1.SumArray(array2);
console.log(arraytotal);

document.getElementById("demo").innerHTML = (arraytotal);
}

The next step for is to find the minimum value and its index.... ...and i have no idea what to do next. I have never approached a forum like this so apologies if the formatting is wrong or the question inappropriate. Any pointers in the right direction would be appreciated!

question from:https://stackoverflow.com/questions/65910719/finding-the-minimim-value-in-an-array-and-its-index-total-beginner-so-any-assi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is a quick sample to sort to arrays.

(function myFunction2() {
  Array.prototype.SumArray = function (arr) {
    var arraytotal = [];
    if (arr != null && this.length == arr.length) {
        for (var i = 0; i < arr.length; i++) {
            arraytotal.push(this[i] + arr[i]);
        }
    }

    return arraytotal;
    }
    
  Array.prototype.MinIndex = function(arr){
    let sortedArray = [];
    if (arr != null){
     let joinedArray = this.concat(arr);
     
     do {
        let minIndx = 0;
      
       for (let i = 0; i < joinedArray.length; i++){
         minIndx = joinedArray[i] < joinedArray[minIndx] ? i : minIndx; 
       }
       
       sortedArray.push(joinedArray[minIndx]);
       joinedArray.splice(minIndx, 1);
       
     } while(joinedArray.length > 0);
    }
    return sortedArray;
  }
})();

var array1 = [1, 9, 10, 6];
var array2 = [9, 6, 7, 8];
var arraytotal = array1.SumArray(array2);
let sortedArray = array1.MinIndex(array2);


document.getElementById("demo").innerHTML = `total: ${arraytotal} sorted: ${sortedArray}`;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...