Angular array filter is not working on a list of string - filter

I have an array of string, and want to filter out a particular string after some operation. But, it seems I am doing something wrong there.
this.displayUser.followers.filter(userId=>userId !== this.loggedUser.userid);
Here, followers is an array of string -> string[] and upon some action (say, unfollow); I want to remove the logged user's id from the displayed user's followers list.
However, this filter operation does not seem to work.
On the other hand I tried using splice which is working perfectly fine.
this.displayUser.followers.splice(
this.displayUser.followers.findIndex(userId=>userId === this.loggedUser.userid)
,1);
I am unable to understand what am I doing wrong in the first approach?

Array.filter does not change the array it performs its action on, but returns a new array with values that passed the condition.
In order to use .filter and have the result saved, you can do:
this.displayUser.followers = this.displayUser.followers.filter((userId) => userId !== this.loggedUser.userid);
This will remove all entries where userId === loggedUser.userid.
.splice on the other hand manipulates the array it performs its actions on, hence you will immediately see the results as expected.

Related

Laravel Collection Filter breaking serialization format

I have a serialized String like this
$string = '[{"name":"FOO"},{"name":""},{"name":"BAR"}]';
I am trying to process it via Laravel Collection's filter method and eliminate items without a defined "name" property.
$collection = collect(\json_decode($string));
$collection = $collection->filter(function($v){
return !empty($v->name);
});
$string = \json_encode($collection->toArray());
dd($string);
Normally I am expecting something like this:
[{"name":"FOO"},{"name":"BAR"}]
But I'm getting something like this:
{"0":{"name":"FOO"},"2":{"name":"BAR"}}
Funny thing is, if I skip the filtering process or return true every time, I keep getting the string in the desired format. Removing the toArray() call has the same result. I don't want to keep the numeric indices as associative object keys.
Why this anomaly? And what should I do to get the serialized data in desired format?
In PHP arrays the index key must be unique.
In your case you have the key 'name' and collection automatically assigns the index key to all items in the collection.
To overcome that problem just call
$string = \json_encode($collection->values());

Eloquent resulting single search result as array not collection

I have some instances where a eloquent is resulting an single array not a collection. Although dd shows it as a collection with a single entry.
For example I have a query in a controller:
$pg = Page::with('getPanels')->where('slug',$slug)->get();
This will return a single result and works fine, so I pass this to a blade template. My complete function is
$pg = Page::with('getPanels')->where('slug',$slug)->get();
return view('front.page',['pg' => $pg]);
As soon as he template is brought in it will fall over at
if (!is_null($pg->headImage))
{$img = asset('images/pages')."/".$pg->headImage;}
and I will get
Property [headImage] does not exist on this collection instance.
If I change the line to
if (!is_null($pg[0]['headImage']))
it will continue OK. This is of course a pain as I would much rather use $pg->headImage.
Can someone enlighten me please?
I have sorted this and I hope it will help other people.
If I use
$pg = Page::with('getPanels')->where('slug',$slug)->first();
it will be just one result (naturally) and therefore
$pg->headImage
will fail as it wants
$pg[0]['headImage']
but if I change the eloquent instead of get(0 to first() (still just one result)
$pg = Page::with('getPanels')->where('slug',$slug)->first();
I can use $pg->headImage or what field I want.

Difference between ListResultDto and List

In my application service, why should I return ListResultDto instead of returning List?
It seems like extra work.
On the frontend, it means I need to access the items property instead of treating the results as an array e.g.
Using ListResultDto
.subscribe((next) => this.entities = next.items);
Using List
.subscrube((next) => this.entities = next);
Using ListResultDto allows you to add additional information about your items in the future without breaking your existing API. If you return items as an array, you are restricting your API.
An example is TotalCount in PagedResultDto, if you want to implement pagination of items.

How to return empty list of records in laravel?

I have some model Task.
If current user has permission then he can see all tasks
return Task::all();
If current user does not have this permission then he can see only empty list
return Task::where('id', 0)->get();
Design is so that user must always get some result, but my functions work with data returned from Task::all() so I can not return empty array or empty Eloquent collection.
What should I do?
You don't want empty array, you don't want empty collection. Maybe you should change the design. Anyway, since you really want to pass an empty list of tasks, manually insert 1 o 2 tasks in the database as first tasks, so their IDs will always be 1 & 2. But leave everything else empty. Then you may always return those 2
return Task::whereIn('id', [1,2])->get();
My suggestion, is to actually fix the design to expect empty object, so you could do something like
return '';
One option would be to return a newly created Task object in an array if the JSON schema has to match exactly. It would look like so:
$emptyTask = new Task();
return [$emptyTask]

RethinkDB: Get only one record from cursor/selection

If I have a query that returns multiple results, how do I get a single element from the selection?
e.g.
r.db("test").table("things") // returns an array of things. I want one of them
Using limit(1) is not what I want because that returns an array.
Rethink DB supports getting the nth element so the query should be:
r.db("test").table("things").nth(0)
In the event that there are no elements, the above will fail with:
Index out of bounds: 0
The solution to this is to return a default object (null in my case) if no element exists.
r.db("test").table("things").nth(0).default(null)

Resources