Strange behavior in JavaScript loop. As a result, only one iteration result is output. How to solve?

  • 0
    The loop behaves very strange.

    let symb = []
    let find = [
    			['К'],
    			['А', 'Р', 'Р', 'М', 'Р', 'Ф'],
    			['М', 'Д']
    			]
    
    let arr = [], res_arr = []
    	
    	function sorts(p_arr, p_symb){
    
    		for(let i = 0; p_arr.length > i; i++){
    
    			index = p_symb.indexOf(p_arr[i])
    			now_index = res_arr.indexOf(p_arr[i])
    
    
    				res_arr[i] = p_symb[index]
    				delete p_symb[index]
    
    		}
    
    		return res_arr
    
    	}
    
    	find.forEach((elem, i, mass)=>{
    
    		symb = [
    			'Р',
    			'А',
    			'М',
    			'Ф',
    			'Р',
    			'Ф',
    			'Р'
    			]
    
    		arr[i] = sorts(mass[i], symb)
    	})
    
    	console.log(arr)


    I expect this conclusion:

    [
    [undefined],
    ['A', 'R', 'R', 'M', 'R', 'F'],
    ['M', undefined]
    ]

    Instead, it turns out:

    [
    ['M', undefined, 'R', 'M', 'R', 'F'],
    ['M', undefined, 'R', 'M', 'R', 'F'],
    ['M', undefined, 'R', 'M', 'R', 'F']
    ]

    But !!! If instead of the autoincrement that provides a loop, you can enter manually arr [1] = sorts (mass [1], symb)
    then this case works out.
    thanks for answers
    JavaScript Max Rivera, Dec 1, 2020

  • 1 Answers
  • 0
    Your res_arr is not reset after each time. Each sorts call in the forEach loop works with the previous res_arr and the old values ​​are not removed. Declare the res_arr array inside the loop:

    function sorts(p_arr, p_symb){
    let res_arr = [];
    //...
    }
    Anonymous

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