-1

I'm quite new to programming.

My use case : I want to find elements that matches this criteria (refer code sample below) as well as elements that doesn't match the criteria and store them in 2 separate variables. Is there any simple methods to do it?

Also I am not able find elements that returns false here. Can someone help me with this.

posts = response.data.posts.filter((m) =>
  m.post.toLowerCase().includes(searchQuery.toLowerCase())
);
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Arsene Wenger
  • 587
  • 4
  • 21

1 Answers1

-2

Do, you want something like this?

let res = [{name: "Peter", age: 29}, {name:"Joseph", age: 23}, {name: "Lily", age: 17}, {name: "Robert", age: 33}, {name: "Ralph", age: 49}] 

let temp1=[];
let temp2=[];

 res.map((item) => item.age <=25 ? temp1.push(item) : temp2.push(item));
 console.log(temp1);
 console.log(temp2);
Deadpool
  • 7,811
  • 9
  • 44
  • 88
  • JavaScript's `.map()` method should be used when you want to "transform" the data in the array to a new array. The `.map()` method returns a new array, and the purpose of the callback is to return the new transformed/mapped values. If you're not using the returned array `.map()` gives you, you shouldn't be using it, and instead be using `.forEach()` (pointing this out [again](https://stackoverflow.com/questions/70448463/how-to-use-one-liner-if-without-else-statement-in-map-in-javascript/70448612#comment124531877_70448612)). More info [here](https://thenewtoys.dev/blog/2021/04/17/misusing-map/) – Nick Parsons Dec 24 '21 at 12:23
  • So basically i am filtering arrays based on a search params.....and hence this line. |posts = response.data.posts.filter((m)=>m.post.toLowerCase().includes(searchQuery.toLowerCase())); Can you help me find elements that returns false for the above line? – Arsene Wenger Dec 24 '21 at 12:23
  • a reason to use map was to return ONE of the arrays and push into the other which is also in the [dupe](https://stackoverflow.com/a/11731128/295783) – mplungjan Dec 24 '21 at 12:25