0

I have selectedSizeList on my state.

selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false}

How do I convert my selectedSizeList to this array?

[2, 3, 4]

Do I have better algorithm than this one? (I assume my solution is not correct)

let array = [];
Objects.keys(selectedSizeList).maps((item) => {
    if(item.value) array.push(item.value)
);
return array;

5 Answers 5

2

You can use array#filter to filter out all keys with true value.

const selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false};
const result = Object
                 .keys(selectedSizeList)
                 .filter(k => selectedSizeList[k])
                 .map(Number);
console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

2

First of all get the array keys using Object.keys() and then use filter() to filter only the true values like this.

var selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false};

var keys = Object.keys(selectedSizeList);

var filtered = keys.filter(function(key) {
    return selectedSizeList[key]
});

console.log(filtered);

Comments

1

Try this (O(n) solution):

selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false};

var arr = [];
for (var key in selectedSizeList) {
    if(selectedSizeList[key]){
       arr.push(key);
    }
}

console.log(arr);

Comments

0

You could use Object.keys() to return an`array that you can then use Array.prototype.filter() on to return a new array.

selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false};
let array = Object.keys(selectedSizeList).filter((item) => {
	if(selectedSizeList[item]) return item;
  });
  //returns [2,3,4]

Comments

0

You can use Object.keys to get an array that you can then filter for values equal to true which will return an array of numbers as a string. You can then map through the array using Number to convert the number strings to numbers which may or may not be necessary depending on what you plan to do with this result. I put this into a function that you can re-use or at least not have your object hard coded with.

var selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false};

// Re-usable function not tied to specific object
const filterForTrueValue = (obj) => Object
                                      .keys(obj)
                                      .filter(k => obj[k])
                                      .map(Number);

console.log(filterForTrueValue(selectedSizeList));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.