2

I have a javascript array like below:

var arr = [ {RoomId:1, RoomName: 'ABC'},
            {RoomId:1, RoomName: 'ABC'},
            {RoomId:1, RoomName: 'ABC'},
            {RoomId:2, RoomName: 'XYZ'},
            {RoomId:2, RoomName: 'XYZ'},
            {RoomId:2, RoomName: 'XYZ'},
           ];

My requirement is something like

  1. Find particular room with RoomId say RoomId = 1.
  2. Remove last few elements from it like remove last 2 elements with RoomId = 1.

So my final array would be like:

var arr = [ {RoomId:1, RoomName: 'ABC'},                
            {RoomId:2, RoomName: 'XYZ'},
            {RoomId:2, RoomName: 'XYZ'},
            {RoomId:2, RoomName: 'XYZ'},
          ];
2
  • Just so you know, that's a JavaScript array. It has no connection with jQuery at all. Commented Jul 1, 2015 at 6:45
  • No apology needed! It's a common point of confusion. I just wanted to help you identify which is which. In any case I'm glad you asked the question, because I hadn't heard of the linq.js library that Anik mentioned - it looks very useful. Commented Jul 1, 2015 at 6:53

2 Answers 2

2

You can use linq.js to maintain this kind of task

Like this

Find particular room with RoomId say RoomId = 1.

Code

var data =Enumerable.From(arr).Where(function(x){return x.RoomId===1;}).ToArray();

Remove last few elements from it like remove last 2 elements with RoomId = 1.

var data =Enumerable.From(arr).Where(function(x){return x.RoomId===1;}).OrderByDescending(function(x){return x.RoomId;}).Skip(2);

arr=data.OrderBy(function(x){return x.RoomId;}).ToArray();
Sign up to request clarification or add additional context in comments.

15 Comments

Thanks, this is really useful, is it free to use and works on all browsers ? Also I forgot to mention that I don't want to make a new array. I want to do everything on same array.
If you wanna hold on same variable your data will be lost
The last line in your code, I think it is retaining the same array right?
Yes. it's replacing same array
data.OrderBy(...).toArray is not a function ... I am getting this error,
|
0

I developed logic for your query like

var destArr=[];
var flag=false;
var count=0;
for(i in arr)
{ 
    if(arr[i].RoomId==1 && flag==false)
    {
        flag = true;
        destArr[count++] = arr[i];              
    }
    else if(flag==true && arr[i].RoomId!=1)
    {
        destArr[count++] = arr[i];              
    }                                   
}   
console.log(destArr);

https://jsfiddle.net/oz6hw8qd/

1 Comment

Thanks, I forgot to mention that I don't want to make a new array. I want to do everything on same array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.