Simple JS Test

by Kashif Imran

HTML

<!-- You must not make any changes to the HTML section. -->
<div id="number1"></div>
<div id="number2"></div>
<div id="number3"></div>
<div id="number4"></div>
<p id="demo"></p>
<p id="demo2"></p>
<p id="demo3"></p>

JavaScript

// NOTE: Do NOT change the arrays and their contents given below. Only work on the tasks A-D using as much of existing code as possible

var arr1 = ['0zzjj', '1299bbkk', '32aaff', '122ddoo'];

var items = [{
  id: 10,
  key: 'a',
  numbers: [1, 2, 3]
}, {
  id: 2,
  key: 'b',
  numbers: [3, 2, 3]
}, {
  id: 3,
  key: 'c',
  numbers: [9, 3, 2]
}];

/*
TASK-A:
Implement the following 'for' loop, so that the value of each div in the HTML section shows the number in its ID after the same number of seconds. For example, the text of <div> with ID='number1' will become "number1" after 1 second, 'number2' will become "number2" after 2 seconds and so on.
*/


for (let i = 0; i < 4; i++) {
  //TODO: Your code for TASK-A
  doSetTimeout(i);
}

function doSetTimeout(i) {
  var string1 = ['number1'];

  setInterval(function() {
    document.getElementById('number1').innerHTML = string1;
    console.log('loop 1');
  }, 1000);

  var string2 = ['number2'];

  setInterval(function() {
    document.getElementById('number2').innerHTML = string2;
    console.log('loop 2');
  }, 2000);

  var string3 = ['number3'];

  setInterval(function() {
    document.getElementById('number3').innerHTML = string3;
    console.log('loop 3');
  }, 3000);

  var string4 = ['number4'];

  setInterval(function() {
    document.getElementById('number4').innerHTML = string4;
    console.log('loop 4');
  }, 4000);
}


/*
TASK-B:
Implement the following function so that it sorts a given array of objects using one of its fields. The function should be able to sort any array of objects with field names other than what's in the example array.
*/

// arr = array of objects
// prop = name of the field/property to be used for sorting
// direction = either 1 for ascending or -1 for descending
function sort(arr, prop, direction = 1) {
  // TODO: Your code here

}
items.sort(function(x, y) {
  var n = x.id - y.id;
  if (n != 0) {
    return n;
  }
  return x.key > y.key;
});


displayItems();


function...