iBlehhz
iBlehhz

Reputation: 586

Map keys into array according to values

what's the most efficient way to map keys into array according to values based on the condition of the value?

For example, I have a map that contains the File object as the key and boolean as the value like this:

map = new Map([
   [file, true],
   [file1, true],
   [file2, false],
   [file3, true],
]);

Can I ask what's the shortcut way of creating an array of file objects if map value === true?

Intended outcome

files = [file,file1,file3];

Appreciate your help thanks!

Upvotes: 2

Views: 1718

Answers (4)

Happy Machine
Happy Machine

Reputation: 1163

The answers above work but if you're after the fastest, perhaps surprisingly using a for loop is faster than the prototype Map and array methods

aka:

myMap = new Map([
    ["file", true],
    ["file1", true],
    ["file2", false],
    ["file3", true],
 ]);

const fastest = (files) => {
    const map = [...files]
    const out = []
    for (let i=0; i<map.length; i++){
        if (map[i][1]){
           out.push(map[i][0])
        }
    }
    return out
}

console.log(fastest(myMap))

https://coderwall.com/p/kvzbpa/don-t-use-array-foreach-use-for-instead There are many articles and a lot of literature about this if you have a look around

Upvotes: 1

schu34
schu34

Reputation: 985

You could use Map.entries with filter and map to achieve this. The basic idea is

  1. Get an array of all keys/values with Map.entries
  2. filter that array to only the entries with the value true
  3. use map to convert from Map entries to array elements.

the code would look something like this.

map.entries().filter(entry=>entry[1]).map(entry=>entry[0]);

Upvotes: 1

Xzandro
Xzandro

Reputation: 977

A simple forEach loop could do the trick here.

const map = new Map([
  ['test', true],
  ['test2', true],
  ['test3', false],
  ['test4', true],
]);

const files = [];

map.forEach((value, key, map) => {
  if (value) {
    files.push(key)
  }

});
console.log(files);

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370689

You can use entries to get the keys and the values of the map, then filter it by whether a value (the condition) is true, and then .map to turn the [key, value] into just the key:

const map = new Map([
   ['file', true],
   ['file1', true],
   ['file2', false],
   ['file3', true],
]);
const files = [...map.entries()]
  .filter(([_, cond]) => cond)
  .map(([key]) => key);
console.log(files);

Upvotes: 1

Related Questions