someuser2491
someuser2491

Reputation: 1968

How to loop through array and push it into a seperate array based on some conditions using react?

i have an array named "all_items" and i want to split that to two arrays named "self" and "others".

I want to loop through each item in "all_items" array and if that item is added by current_user then push it to "self" array if not "others" array

item = {
    id: 0,
    owner_id: 1, 
    name: "name",
}

Below is the algorithm,

group = () => {
    const self = [];
    const others = [];
    for each item
        if item is uploaded by current_user
            self.push(item)
        else
            others.push(item)
    return {self, others}
}

How can i implement the above in react or javascript. Could someone help me with this. thanks.

Upvotes: 0

Views: 64

Answers (3)

harisu
harisu

Reputation: 1416

A much better aproach is to use filter as follows

const group = () => {
  const items = [
 {
    id: 0,
    owner_id: 1, 
    name: "name",
},
 {
    id: 2,
    owner_id: 2, 
    name: "user 2",
}
];
let current_user = { id: 1, name: "current user"}

const result = items.filter(item => item.owner_id != current_user.id);
const result2 = items.filter(item => item.owner_id == current_user.id);

  return { result, result2}
}

Upvotes: 1

Emily Zhai
Emily Zhai

Reputation: 112

There are a couple ways to approach this problem. I think the cleanest approach in terms of readability and length is to leverage Javascript's built in prototype Array.filter() method.

const self = all_items.filter(item => item.owner === current_user);
const others = all_items.filter(item => item.owner !== current_user);

Or for a solution that mirrors your example algorithm more closely, you can iterate over all_items with forEach() and push values to self and others as you go.

const self = [];
const others = [];

all_items.forEach(item => {
  if (item.owner === current_user) {
    self.push(item);  
  } else {
    others.push(item);
  }
});

**Also note that === will compare both type and value.

Upvotes: 0

Denis Alemán
Denis Alemán

Reputation: 595

You can use filter

var all_items = [{
    id: 0,
    owner_id: 1, 
    name: "Matt",
},
{
    id: 1,
    owner_id: 2, 
    name: "Dave",
},
{
    id: 2,
    owner_id: 1, 
    name: "Mike",
},
{
    id: 3,
    owner_id: 3, 
    name: "Jack",
},
{
    id: 4,
    owner_id: 1, 
    name: "Paul",
}];

var current_user = {
    id: 1
};

// self
console.log(all_items.filter(function(item){
    return item.owner_id === current_user.id;
}));

// others
console.log(all_items.filter(function(item){
    return item.owner_id !== current_user.id;
}));

Upvotes: 0

Related Questions