1

I have the following loop in javascript array A

[
    {
    "key1": "value121212",
    "booleankey": false,
    },
    {
    "key1": "value143434",
    "booleankey": false,
    },
    {
    "key1": "value1454545",
    "booleankey": true,
    }
]

I need to loop the above array A and create another array B which includes booleankey, Requirement is, when i create the new array B, the entry with "booleankey": true, should come first. Initial array A can have the booleankey as true as the last entry,

How can i make sure to get the new array B with booleankey true always on the first ? This is how arrayB is created:

createArrayB(entry) {
    arrayA.map((entry) => {
            return  {
                newkey: entry.key1,
                newbooleankey: entry.booleankey,
            }
        });
2
  • 3
    Sort the array before you map over it? After you map over it? Commented Jul 30, 2019 at 11:12
  • as @jonrsharpe said, just sort it, and B is what you get as an output Commented Jul 30, 2019 at 11:14

1 Answer 1

0

You could sort by the boolean key with the delta of it. This moves all true property to top.

var array = [{ key1: "value121212", booleankey: false }, { key1: "value143434", booleankey: false }, { key1: "value1454545", booleankey: true }];

array.sort((a, b) => b.booleankey - a.booleankey);

console.log(array);

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.