Filter files of the same date ? JS

Asked

Viewed 17 times

-1

Hello, I have an array with several objects I would like to know how to filter objects that have date equal to "02" for example:

 let arr = [
  { name: "file0.xml", date: "02", size: "10823" },
  { name: "file1.xml", date: "02", size: "10823" },
  { name: "file2.xml", date: "03", size: "10823" },
  { name: "file3.xml", date: "02", size: "10823" },
  { name: "file4.xml", date: "03", size: "09504" },
  { name: "file5.xml", date: "02", size: "09504" },
  { name: "file6.xml", date: "04", size: "09504" },
  { name: "file7.xml", date: "04", size: "13628" },
  { name: "file8.xml", date: "05", size: "13628" },
  { name: "file9.xml", date: "02", size: "13628" },
  { name: "file10.xml", date: "06", size: "0" }
];

console.log('\n\n---> Meus Dados da Base \n\n')
console.log(arr)
console.log('\n\n Fim <---\n\n')

let obj = arr.find(o => o.date ==='02');
console.log(obj)

Thus display ::

[ { name: 'file0.xml', date: '02', size: '10823' },
  { name: 'file1.xml', date: '02', size: '10823' },
  { name: 'file3.xml', date: '02', size: '10823' },
  { name: 'file5.xml', date: '02', size: '09504' },
  { name: 'file9.xml', date: '02', size: '13628' }
]
  • Instead of arr.find(o => o.date ==='02'), which will only find the first occurrence, use arr.filter(o => o.date ==='02') to find all occurrences.

1 answer

1


The method find will look for an array item that satisfies the condition you place inside the callback, returning the first element that satisfies it.

To return a new array with all the elements that satisfy the condition, you must use the method filter, as also indicated in comments.

Thus:

const arr = [
  { name: "file0.xml", date: "02", size: "10823" },
  { name: "file1.xml", date: "02", size: "10823" },
  { name: "file2.xml", date: "03", size: "10823" },
  { name: "file3.xml", date: "02", size: "10823" },
  { name: "file4.xml", date: "03", size: "09504" },
  { name: "file5.xml", date: "02", size: "09504" },
  { name: "file6.xml", date: "04", size: "09504" },
  { name: "file7.xml", date: "04", size: "13628" },
  { name: "file8.xml", date: "05", size: "13628" },
  { name: "file9.xml", date: "02", size: "13628" },
  { name: "file10.xml", date: "06", size: "0" }
];

const filtered = arr.filter(o => o.date ==='02');

console.log(filtered)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.