0

I have an array of object of which I want to check if the any of the object has a title 'food' before checking for others but at the moment, it checks sequentially. Bellow is my code

let db = {
  users: [{
      id: 1,
      title: "food"
    },
    {
      id: 2,
      title: "stone"
    },
    {
      id: 3,
      title: "food"
    }
  ]
}

for (let index in db.users) {
  if (db.users[index].title === "food") {
    console.log("Its food");
    continue;
  }
  console.log("Its not food");
}

With the code above, I get the following result

Its food
Its not food
Its food

How do i do it such that i it checks for all food before any other title so i get the result

Its food
Its food
Its not food 

Thanks.

3
  • Why not use if and else? Commented May 13, 2019 at 12:49
  • Sorry, not sure what your are trying to achieve. But you may filter your array first maybe ? Like this : db.users.filter(user => user.title === 'food') Commented May 13, 2019 at 12:50
  • At any point of time there will be either of the two - food or no food. So if you want it in order, better use loops separately. Commented May 13, 2019 at 12:50

5 Answers 5

2

You could sort the "food" items to the beginning of the array and then loop through it

let db = { users: [ { id: 1, title: "food" },  { id: 2, title: "stone" },  { id: 3, title: "food" }] };

db.users.sort((a, b) => (b.title === "food") - (a.title === "food"))
        .forEach(a => console.log(a.title === "food" ? "It's food" : "It's not food"))

Subtracting booleans returns 1, -1 or 0

true - false === 1
false - true === -1
true - true === 0

So, if a.title === food and b.title isn't, -1 will be returned from the compareFunction. So, a will be placed ahead of b in the array.

Sign up to request clarification or add additional context in comments.

Comments

1

You can maintain an array and use Array.push (adds at last) if Its not food and use Array.unshift (adds at the beginning) to add the value at beginning if Its food.

let db = {users: [{id: 1,title: "food"},{id: 2,title: "stone"}, {id: 3,title: "food"}]};

let result = [];
for(let index in db.users) {
    if(db.users[index].title === "food") {
        result.unshift("Its food");
        continue;
    }
    result.push("Its not food");
}

console.log(result);

1 Comment

@WhiteHox - Then you will need to sort the array first!
1

If you want to print first all foods and then items which are not food , then you can use two different loop and print seperately

first for loop for all foods

for(let index in db.users) {
    if(db.users[index].title === "food") {
        console.log("Its food");
    }
}

second for loop for all items which are not a food.

for(let index in db.users) {
    if(db.users[index].title != "food") {
        console.log("Its not food");
    }
}

To reduce iterations we can use filter and save filtered items separately and then iterate though each array

let foodItems = db.users.filter(user => user.title === 'food')
let nonFoodItems = db.users.filter(user => user.title != 'food')

now iterate through each array which are filtered based on title

Comments

1

You can use Array.prototype.sort() method to sort them and map over them

let db = {
    users: [
        {
           id: 1,
            title: "food"
        }, 
        {
            id: 2,
            title: "stone"
        }, 
        {
            id: 3,
            title: "food"
        }
    ]
}

const sortTitle = (a,b) => (a.title === "food" && b.title !== "food") ? -1 : 1;
const mapOutput = it => { if(it.title === "food") { console.log("Its food"); } else { console.log("Its not food");}};

db.users
.sort(sortTitle)
.map(mapOutput);

Comments

1

You could map the strings, sort and reverse the array for getting the right text in wanted order.

let db = { users: [ { id: 1, title: "food" },  { id: 2, title: "stone" },  { id: 3, title: "food" }] }, 
    msg = db.users
        .map(({ title }) => title === 'food' ? "It's food" : "It isn't food")
        .sort()
        .reverse();

msg.forEach(m => console.log(m));

You could take a generator and get the values in the wanted order.

function* getInOrder([{ title }, ...rest]) {
    if (title === "food") {
        yield "It's food";
        if (rest.length) yield* getInOrder(rest);
    } else {
        if (rest.length) yield* getInOrder(rest);
        yield "It isn't food";
    }
}
let db = { users: [ { id: 1, title: "food" },  { id: 2, title: "stone" },  { id: 3, title: "food" }] };

[...getInOrder(db.users)].forEach(m => console.log(m));

1 Comment

Thanks but i wasn't trying to get the result in wanted order but execute in wanted order

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.