Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Print all even values in all object key end with odd value

I want to print all even values in all object key end with odd value but the coding I made just now is only specified for arr1, arr3, and arr5. Can anyone suggest me how to fix ‘let oddArr’ method (maybe in loop) so that when I changed arr1 into arr7, the result would be the same.

var num = {
    arr1 : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    arr2 : [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
    arr3 : [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
    arr4 : [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
    arr5 : [41, 42, 43, 44, 45, 46, 47, 48, 49, 50],
    };

    let oddArr = [...num.arr1, ...num.arr3, ...num.arr5] //need some correction here
    let evenNum = oddArr.filter(number => number % 2 == 0);

    console.log(evenNum.toString());
    
    //help me fix 'let oddArr' (maybe in loop method) so that when I changed the object of the array (e.g: arr1 -> arr7) it would come out with the same result 
    
    //the result/output should be 2,4,6,8,10,22,24,26,28,30,42,44,46,48,50 based on var num

e same.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can try like below using for in loop and it works with any last character as odd.

var num = {
  arr1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  arr2: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
  arr3: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
  arr4: [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
  arr7: [41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
};

let oddArr = [];
for (let key in num) {
  if (key.charAt(key.length - 1) % 2 !== 0) {
    oddArr = [...oddArr, ...num[key]];
  }
}

let evenNum = oddArr.filter((number) => number % 2 === 0);

console.log(evenNum.toString());

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading