Need to find identical numbers in an array?

  • 0
    There are two arrays:

    let km = [25, 45, 95, 125, 150, 200, 325, 250, 165, 350]
    
    let cof = [1, 1.5, 1, 1.5, 1.2, 1.5, 1 , 0.5, 1.2, 1.5];


    I need to find the same numbers in an array ( cof ) and add the numbers of another array ( km ), depending on what index the same numbers had in ( cof ). For example:
    In this variant, the correct answer is 445 (25 + 95 + 325), 720 (45 + 125 + 200 + 350), 315 (150 + 165)
    since in the array the same numbers are at indices 0, 2, 6 and 1, 3, 5, 9 and 4, 8.

    My code looks like this:
    let km = [25, 45, 95, 125, 150, 200, 325, 250, 165, 350]
    
    let cof = [1, 1.5, 1, 1.5, 1.2, 1.5, 1 , 0.5, 1.2, 1.5];
    
    let itog = [];
    
    
    	for (let i = 0; i < cof.length; i++) {
    		
    		for(let k = i + 1; k < cof.length; k++){
    			
    			if(cof[i] === cof[k]){
    
    				itog[i] = km[i] + km[k];
    
    				
    			}
    
    		}
    		
    	}
    	console.log(itog)


    But he writes down only the sum of two identical numbers, I can't understand how to do it differently.
    JavaScript Anonymous, Feb 19, 2019

  • 1 Answers
  • 0
    const km = [25, 45,  95, 125, 150, 200, 325, 250, 165, 350]

    const cof = [1, 1.5, 1, 1.5, 1.2, 1.5, 1 , 0.5, 1.2, 1.5];

    // как то так
    const res = cof.reduce((a,v,i)=>(a[v]=(a[v]||0)+km[i],a),{});

    console.log(res); // { 1: 445, "1.5": 720, "1.2": 315, "0.5": 250 }

    console.log(Object.values(res)); // [445, 720, 315, 250];
    Natalie Burton

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!