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

Function with array and object

I have an array and an object and i would like a function samePrice(arr,obj) like this:

const arr = [0,1,2];
const obj = {
    0: 10,
    1: 10,
    2: 10,
    3: 12,
};

// samePrice(arr,obj) => true

const arr = [0,3];
const obj = {
    0: 10,
    1: 10,
    2: 10,
    3: 12,
};

// samePrice(arr,obj) => false

I have a solution with forEach but the function is 10+ lines long.. and I am sure there is a better solution.

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 :

Basically, what you’re doing is checking that every element is the same as the first:

const samePrice = (arr,obj) => arr.every(x => obj[x] == obj[arr[0]])

const arr = [0,1,2];
const obj = {
    0: 10,
    1: 10,
    2: 10,
    3: 12,
};

console.log(samePrice(arr,obj)); // => true

const arr2 = [0,3];
const obj2 = {
    0: 10,
    1: 10,
    2: 10,
    3: 12,
};

console.log(samePrice(arr2,obj2)); // => false
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