0

I have a very simple arrayMap in a computed observable like this:

self.Employees = ko.computed(function() {
    return ko.utils.arrayMap(self.EmployeeData(),

      function(data) {

        return {

          Name: data.EmployeeName,
          value: data.EmployeeID
        }

      });

  })

The data is JSON:

[{"Name" : "John"}, {"EmployeeID" : "1w23"}]

Is there a way to have a specific Employee at the top of the list based on some condition? In a nutshell when I bind that data to en element a record is the first at the top?

Asynchronous
  • 3,917
  • 19
  • 62
  • 96
  • *Is there a way to have a specific Employee at the top of the list based on some condition?* - Yes, but **what condition?** Just one record at the top or an order for the entire array? – webketje Dec 20 '15 at 01:24

1 Answers1

1

You simply have to reorder the self.EmployeeData() array, and put it at the top of the list, depending on the condition.

That's an easy JavaScript task. For an example, please, see this:

Move an array element from one array position to another

Or, if you don't mind using lodash, you can use a function like this:

var moveToStart = function(list, predicate) {
  var found = _.remove(list, predicate);
  list.unshift.apply(list, found);
};

As shown in this snippet:

var list = [1,2,3,4,5];

var moveToStart = function(list, predicate) {
    var found = _.remove(list, predicate);
    list.unshift.apply(list, found);
};

$('#original').text(JSON.stringify(list));

moveToStart(list, function(e) { return e == 3;})
$('#moved3').text(JSON.stringify(list));

moveToStart(list, function(e) { return e%2 == 0;})
$('#movedEven').text(JSON.stringify(list));

moveToStart(list, function(e) { return e == 500;})
$('#moved500').text(JSON.stringify(list));


var list2 = [
 {name:'John', age: 41, },
 {name:'Frank', age: 23 },
 {name:'Anna', age: 37},
 {name:'Norah', age: 3}
];

$('#originalPeople').text(JSON.stringify(list2,null,2));

moveToStart(list2, function(p) { return p.age < 30});
$('#movedPeople').text(JSON.stringify(list2,null,2));
p {
  font-family: Segoe, Arial;
  font-weight: bold;
  margin: 15px 0 0 0;
}

pre {
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>Original:</p>
<pre id="original"></pre>
<p>After 3 to start:
  moveToStart(list, function(e) { return e == 3;})
<pre id="moved3"></pre>
<p>After even numbers to start: 
  moveToStart(list, function(e) { return e%2 == 0;})</p>
<pre id="movedEven"></pre>
<p>After non-existen number to start: 
  moveToStart(list, function(e) { return e == 500;})</p>
<pre id="moved500"></pre>
<br/>
<br/>
<p>Original list of persons<p>
<pre id="originalPeople"></pre>
<p>After moving younger than 30 to start<br/>
moveToStart(list2, function(p) { return p.age &lt; 30});
</p>
<pre id="movedPeople"></pre>
Community
  • 1
  • 1
JotaBe
  • 38,030
  • 8
  • 98
  • 117