1

So inside the folders array. I want to print out the 'name' of the folders that don't have null as their size.

let folders = [
  {
    name:'user_name',
    size: 5455,
    information: ' '
    },
  {
    name:'untitled',
    size: 545343,
    information: 'no description'
  },
  {
    name:'new_user',
    size: null
  }
];

So i've made this code in order to get the names of the folders that don't have null as their size but when I test it, it only prints out all the arrays. I can't quite figure out what I'm doing wrong.

folders.forEach((item) => {
  let info = folders.filter((f) => {
    if (f.size !== null);
    return item.name
  })
  console.log(info)
});

2 Answers2

1

One problem is that if (f.size !== null); should not have a trailing semicolon - that will make the test meaningless, because no matter whether it's null or not, the semicolon will mean that the line that follows will be executed regardless. Another is that filter always returns the original item in the array, if the test passes - for what you're doing, you might use filter (to filter out null sizes) followed by map (to get to the names):

let folders = [
  {
    name:'user_name',
    size: 5455,
    information: ' '
    },
  {
    name:'untitled',
    size: 545343,
    information: 'no description'
  },
  {
    name:'new_user',
    size: null
  }
];
console.log(
  folders
    .filter(({ size }) => size !== null)
    .map(({ name }) => name)
);

If you wanted to achieve it in a single iteration over the array, use reduce to filter and map at the same time:

let folders = [
  {
    name:'user_name',
    size: 5455,
    information: ' '
    },
  {
    name:'untitled',
    size: 545343,
    information: 'no description'
  },
  {
    name:'new_user',
    size: null
  }
];
console.log(
  folders.reduce((a, { name, size }) => {
    if (size !== null) a.push(name);
    return a;
  }, [])
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

To achieve this, consider using Array#filter() in combination with Array#map().

First, use filter() to isolate the folder items where the size is not null:

.filter(folder => folder.size !== null)

and then use map() to transform each folder item in the filtered result, to the name of that folder:

.map(folder => folder.name)

The complete example can be seen as:

let folders = [
  {
    name:'user_name',
    size: 5455,
    information: ' '
    },
  {
    name:'untitled',
    size: 545343,
    information: 'no description'
  },
  {
    name:'new_user',
    size: null
  }
];

let result = folders
.filter(folder => folder.size !== null)
.map(folder => folder.name)

console.log(result)
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65