how to sort an integer combined array in javascript - javascript

I have an array like this in JS:
var a = ["1", "2", "1_10", "1_22", "2_12", "3", "14", "1_15", "3_31", "14_25", "2_18"];
and I need to sort it, in order to look like this:
["1", "1_10", "1_15", "1_22", "2", "2_12", "2_18", "3", "3_31", "14", "14_25"];
I tried using a function like the one in this fiddle http://jsfiddle.net/r7vQP/ but I am getting a wrong answer (["1", "14", "14_25", "1_10", "1_15", "1_22", "2", "2_12", "2_18", "3", "3_31"]).

Try this:
var b = a;
for (var i = 0; i < b.length; i++) {
b[i] = b[i].replace('_', '.');
}
b.sort(function (a, b) { return a - b });
for (var y = 0; y < b.length; y++) {
a[y] = b[y].replace('.', '_');
}

function numericSort(a, b) {
return a - b;
}
a.map(function (e) {
return parseFloat(e.replace("_", "."));
})
.sort(numericSort)
.map(function (e) {
return e.toString().replace(".", "_");
})

var a = ["1", "2", "1_10", "1_22", "2_12", "3", "14", "1_15", "3_31", "14_25", "2_18"];
function sortByFloat (a,b)
{
a=parseFloat (a.replace ("_","."));
b=parseFloat (b.replace ("_","."));
if (a<b) return -1;
if (a>b) return 1;
if (a==b) return 0;
}
a.sort (sortByFloat);
return a-b would be faster instead of the three if conditions

function to_dot(s) { return s.replace('_','.') }
function from_dot(n) { return n.replace('.','_') }
a.map(to_dot).sort(function(a,b){return a-b}).map(from_dot)
["1", "1_10", "1_15", "1_22", "2", "2_12", "2_18", "3", "3_31", "14", "14_25"]

Related

How to make a loop with this array?

in Javascript for example I have this array:
var ids = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
(The number of objects in the array changes constantly)
How could I get this result (a new array), and how can I separate it? for example in 3 (I probably need to make a loop for this)
var urls= ["example.com/?id0=1&id1=2&id2=3", "example.com/?id3=4&id4=5&id5=6", "example.com/?id6=7&id7=8&id8=9", "example.com/?id9=10"]
Thanks.
Use .map to add id to the ids and join the resulting array with &
var ids = ["10000000", "2000000", "1234567", "7654321", "7777777"];
var url = "example.com/?" + ids.map((id, ndx) => `id${ndx}=${id}`).join("&");
console.log(url);
EDIT
Based on the edited question, you can create function to split the array of ids into chunks and use the same code as before, map the chunks to add id and join them with &
var ids = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "xxx"];
const generateUrls = (ids, n = 3) => {
var i,
j,
temparray,
urls = [],
ndx = 0;
for (i = 0, j = ids.length; i < j; i += n) {
temparray =
"example.com/?" +
ids
.slice(i, i + n)
.map(id => `id${ndx++}=${id}`)
.join("&");
urls.push(temparray);
}
return urls;
};
const result = generateUrls(ids, 3);
console.log(result);

display x amount of two Randomize arrays and output the same “randomized” result

How would I take two arrays and with 20 elements each and display 5 at random. not the first 5 but 5 random ones. this is a drag and drop acitiby that I want to be able to redo hence the randomized selection.
I tried using something like match1.length = match1.length < 5 ? match1.length : 5; and it kinda worked but it would display the 5 correct one and the rest would show up as null blank spaces
var match1 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"];
//this are drop target (#rightCol)
var match2 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"];
This is what I am using to randomize the arrays
var i=0, len= match1.length, next, order=[];
while(i<len)order[i]= ++i;
order.sort(function(){return Math.random()+.5});
for(i=0; i<len; i++){
next=order[i];
match1.push('<li data-index="' + (i + 1) + '">' + match1[next]);
match2.push('<li data-index="' + (i + 1) + '">' + match2[next]);
}
match1.splice(1, len);
match2.splice(1, len);
but it display all 20 at once and I only want 5 at a time so it can be redone multiply times.
This is the rest of the code.
//shuffle the arrays
arrMatch1 = shuffle(match1);
arrMatch2 = shuffle(match2);
//insert them into DOM
$('#source').html(match1.join(''));
$('#target').html(match2.join(''));
}
function shuffle(v) {
for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
return v;
}
function initQuiz() {
$('#source li').draggable(
{
revert: true,
revertDuration: 600,
cursor: "all-scroll"
});
var totalScore = 0;
$('#score').text(totalScore + ' correct answer');
$('#target li').droppable(
{
accept : function(draggable)
{
if(parseInt(draggable.data('index'), 10) ===
parseInt($(this).data('index'), 10))
{
return true;
}
else
{
return false;
}
},
drop: function( event, ui )
{
var that = $(this);
that.addClass( "ui-state-highlight").html('Correct!');
that.droppable('disable');
ui.draggable.addClass('correct ui-state-active');
(ui.draggable).draggable('disable');
totalScore++;
$('#score').text(totalScore + ' matching answer');
if($('li.correct').length == 10)
{
$( "#dialog-complete" ).dialog({
resizable: false,
modal: true
});
}
}
});
}

Randomize two arrays and output the same "randomized" result

I am using JavaScript/jQuery to random two list of arrays, one with the word and the other there definition.
I want each load to select 5 out of the available 10 in each array so that were I am running into issues.
I am able to randomize both arrays but I need both to output the same "random" result so they can match both sides.
var match1 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
var match2 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
and is current output is something like
match1 = 2 5 7 8 3
match1 = 1 3 9 4 5
and I need somthing like this
match1 = 7 5 2 8 1
match1 = 7 5 2 8 1
I am new to JavaScript so sorry for the messy code.
function createQuizLayout() {
//this are the draggables (#leftCol)
var match1 = ["1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10"
];
//this are drop target (#rightCol)
var match2 = ["1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10"
];
function randomSort(min, max) {
return (parseInt(Math.random() * 10) % 2);
}
(match1.sort(randomSort));
(match2.sort(randomSort));
var arrMatch1 = [];
for (var i = 0; i < match1.length; i++) {
arrMatch1.push('<li data-index="' + (i + 1) + '">' + match1[i] + '</li>');
arrMatch1.length = arrMatch1.length < 5 ? arrMatch1.length : 5;
}
var arrMatch2 = [];
for (var i = 0; i < match2.length; i++) {
arrMatch2.push('<li data-index="' + (i + 1) + '">' + match2[i] + '</li>');
arrMatch2.length = arrMatch2.length < 5 ? arrMatch2.length : 5;
}
//shuffle the arrays
arrMatch1 = shuffle(arrMatch1);
arrMatch2 = shuffle(arrMatch2);
//insert them into DOM
$('#source').html(arrMatch1.join(''));
$('#target').html(arrMatch2.join(''));
}
function shuffle(v) {
for (var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
return v;
}
I'm pretty sure you missed the part How to shuffle the two arrays the right (same) way :)
Have a look at this code:
var match1 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
var match2 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
var i=0, len= match1.length, next, order=[];
while(i<len)order[i]= ++i;
order.sort(function(){return Math.random()-.5});
for(i=0; i<len; i++){
next=order[i];
match1.push(match1[next]);
match2.push(match2[next]);
}
match1.splice(1, len);
match2.splice(1, len);
console.log(match1)
console.log(match2)
To change your arrays in place, get the shuffled order first and add the new arrangements to the end of the existing array (match1).
Then splice out from index 1 splits the array into your two (same way shuffled) arrays with exactly the same length.

Adding object properties into a JSON object

I have a JSON object in this format.
[
{
"name": "schoolname",
"line id": "0",
"time": "4-5",
"minage": "15",
"maxage": "35"
},
{
"name": "studentname1",
"line id": "1",
"class": "A"
},
{
"name": "studentname2",
"line id": "2",
"class": "B"
}
]
What I want to do
From a set of specified headers, get it from the "line id" : "0" and set it to the other items.
For Example:
headers = ["time", "minage", "maxage"]
I get these from the "line id" : "0" and give it to others like this.
[
{
"name": "schoolname",
"line id": "0",
"time": "4-5",
"minage": "15",
"maxage": "35"
},
{
"name": "studentname1",
"line id": "1",
"class": "A",
"time": "4-5",
"minage": "15",
"maxage": "35"
},
{
"name": "studentname2",
"line id": "2",
"class": "B",
"time": "4-5",
"minage": "15",
"maxage": "35"
}
]
and then remove the element with "line id" : "0", like this:
[
{
"name": "studentname1",
"line id": "1",
"class": "A",
"time": "4-5",
"minage": "15",
"maxage": "35"
},
{
"name": "studentname2",
"line id": "2",
"class": "B",
"time": "4-5",
"minage": "15",
"maxage": "35"
}
]
It is said that the 1st element would be a "line id" : "0".
What I've tried:
var headers = ["time", "minage", "maxage"]
var data =
[
{
"name": "schoolname",
"line id": "0",
"time": "4-5",
"minage": "15",
"maxage": "35"
},
{
"name": "studentname1",
"line id": "1",
"class": "A"
},
{
"name": "studentname2",
"line id": "2",
"class": "B"
}
];
for(var i = 1; i < data.length; i++)//iterate over the data leaving the 1st line
{
for(var j = 0; j < headers.length; j++)//add each header to the data lines
{
data[i][headers[j]] = data[0][headers[j]];
}
}
data.splice(0,1);
Everything works fine and as intended. Is there a way to reduce the time-complexity of this and make it more efficient.
This now has a time complexity of O(n * m).
Is there a way around of adding these few objects to all the elements? As the key value pairs to be added for all the entries remain the same.
You can use Object.defineProperties like
var arr = [{
"name": "schoolname",
"line id": "0",
"time": "4-5",
"minage": "15",
"maxage": "35"
}, {
"name": "studentname1",
"line id": "1",
"class": "A"
}, {
"name": "studentname2",
"line id": "2",
"class": "B"
}],
headers = ["time", "minage", "maxage"];
function addHeaders(arr, headers) {
var header = arr.splice(0, 1)[0],
propObj = headers.reduce(function(acc, el) {
acc[el] = {
value: header[el],
writable: true,
enumerable: true
};
return acc;
}, {});
for (var i = 0, len = arr.length; i < len; i++) {
Object.defineProperties(arr[i], propObj);
}
return arr;
}
document.getElementById('r').innerHTML = 'initial: ' + JSON.stringify(arr,null,2) + '<br/>';
document.getElementById('r').innerHTML += 'result: ' + JSON.stringify(addHeaders(arr, headers),null,2);
<pre id="r"></pre>
Is that data format you have fixed? You should consider doing something more like
school
-> info (name, etc.)
-> [classes]
-> info
-> [student_ids]
-> [students]
-> info (id)
If you can't change your format. You could do something like what you want with Underscore.js#default. Assuming line_id=0 is always data[0]:
var keys = ['minage','maxage','time'];
var temp = _.pick(data.shift(),keys);
data.forEach(function(e, i, a) {
a[i] = _.default(e,temp);
});
It doesn't really reduce your complexity because you're basically looking an array of size N and update properties count M, meaning you'll have a complexity of O(N*M). If you want something less complex, don't move/copy the data. Reuse it in the current form.
Since you say that you are copying the same values from the 0th element, you can store it in a variable(say new_data) and then iterate through the data array and just add them there.
This is as complex as iterating through data and inserting key-val pairs.
Something like this -
> new_data = {}
//Getting all the content with header keys in data into new_data
> headers.forEach(function(v){new_data[v] = data[0][v]})
//Storing the new_data
> new_data
Object {time: "4-5", minage: "15", maxage: "35"}
//Adding the new_data into data
> data.forEach(function(d_val){
for(k_nd in new_data){
d_val[k_nd] = new_data[k_nd];
}
});
//Removing the 0th array element
> data.splice(0, 1)
//Checking it
> JSON.stringify(data[0])
"{"name":"studentname1","line id":"1","class":"A","time":"4-5","minage":"15","maxage":"35"}"
Using lodash library:
var headers = ["time", "minage", "maxage"];
var data = [{
"name": "schoolname",
"line id": "0",
"time": "4-5",
"minage": "15",
"maxage": "35"
}, {
"name": "studentname1",
"line id": "1",
"class": "A"
}, {
"name": "studentname2",
"line id": "2",
"class": "B"
}];
var temp = _.pick(data[0], headers);
data.splice(0, 1);
for (var i = 0; i < data.length; i++) {
_.merge(data[i], temp);
}
var result = JSON.stringify(data);
$('#result').text(result);
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
EDIT:
Found a significant performance booster, faster than all other tested solutions so far: extracting one of the loops and applying via: new Function(...). Essentially an eval-like approximation of Object.defineProperties(...). Have added this to the performance tests below:
function addHeadersNewFunc(arr, headers) {
//console.time('addHeadersNewFunc');
var header = arr.shift(),
funcBody = ['return item;'],
headerPropName,
setProps;
for(var h = headers.length; h--;) {
headerPropName = headers[h];
funcBody.unshift('item["' + headerPropName + '"]="' + header[headerPropName] + '";'); //unshift since loop is reversed and we want props in same add order as other implementations, and we've already added our first line
}
setProps = new Function('item', funcBody.join('')); //warning, this is a form of 'eval()'...
for (var i = arr.length; i--;)
{
setProps(arr[i]);
}
//console.timeEnd('addHeadersNewFunc');
return arr;
}
Some interesting results testing a few different approaches. I've only just whipped up the performance testing code, happy for any recommended improvements. I've also added some additional implementations - a string replacement approach, and a lazy getter.
In general it looks like the original loop outperforms most of the other suggestions; except for the implementation by #Chris Anderson-MSFT using Underscore's defaults when tested in Chrome, which appeared to actually be faster (didn't fare as well in IE, however). Otherwise, the lazies performed consistently well, also. (* EDIT: as per above, implementation using new Function() eventually found to be fastest; for large objects/iterations, significantly).
Sample output of the below snippet (Chrome 43):
Items: 2000
Output of functions is all consistent: true
Testing...
addHeadersOrig x 1000: [Avg] 2.3977ms, [Min] 2.3170ms, [Max] 2.8280ms
addHeadersDefineProp x 1000: [Avg] 6.3481ms, [Min] 6.1010ms, [Max] 15.1750ms
addHeadersStrReplace x 1000: [Avg] 3.0551ms, [Min] 2.6630ms, [Max] 5.9910ms
addHeadersUnderscoreDefaults x 1000: [Avg] 1.4344ms, [Min] 1.1800ms, [Max] 9.5100ms
addHeadersLazy x 1000: [Avg] 2.4529ms, [Min] 2.3460ms, [Max] 6.0770ms
addHeadersLazyMemo x 1000: [Avg] 2.4837ms, [Min] 2.3760ms, [Max] 3.8420ms
addHeadersNewFunc x 1000: [Avg] 0.0959ms, [Min] 0.0430ms, [Max] 0.5070ms
(function() {
"use strict";
var arr = [{
"name": "schoolname",
"line id": "0",
"time": "4-5",
"minage": "15",
"maxage": "35"
}, {
"name": "studentname1",
"line id": "1",
"class": "A"
}, {
"name": "studentname2",
"line id": "2",
"class": "B"
}],
headers = ["time", "minage", "maxage"];
//add some more...
for (var i = 3, iLen = 2000; i < iLen; i++) {
arr.push({
name: "studentname" + i,
"line id": String(i),
"class": "C"
});
}
function addHeadersOrig(arr, headers) {
//console.time('addHeadersOrig');
for (var i = 1; i < arr.length; i++) //iterate over the data leaving the 1st line
{
for (var j = 0; j < headers.length; j++) //add each header to the data lines
{
arr[i][headers[j]] = arr[0][headers[j]];
}
}
arr.splice(0, 1);
//console.timeEnd('addHeadersOrig');
return arr;
}
function addHeadersDefineProp(arr, headers) {
//console.time('addHeadersDefineProp');
var header = arr.splice(0, 1)[0],
propObj = headers.reduce(function headerReduce(acc, el) {
acc[el] = {
value: header[el],
writable: true,
enumerable: true
};
return acc;
}, {});
for (var i = 0, len = arr.length; i < len; i++) {
Object.defineProperties(arr[i], propObj);
}
//console.timeEnd('addHeadersDefineProp');
return arr;
}
function addHeadersStrReplace(arr, headers) {
//console.time('addHeadersStrReplace');
var header = arr.shift(),
propObj = {};
for (var i = 0; i < headers.length; i++) {
propObj[headers[i]] = header[headers[i]];
}
//stringify the array, replace each '}' with a ',' followed by the the stringified propObj (minus its opening bracket) which brings its own closing bracket to make up for the one we replaced; then parse back to an object
arr = JSON.parse(JSON.stringify(arr).replace(/\}/g, ',' + JSON.stringify(propObj).slice(1)));
//console.timeEnd('addHeadersStrReplace');
return arr;
}
//only runs using lodash, not underscore
function addHeadersLodashMerge(arr, headers) {
//console.time('addHeadersLodashMerge');
var temp = _.pick(arr.shift(), headers);
for (var i = 0; i < arr.length; i++) {
_.merge(arr[i], temp);
}
//console.timeEnd('addHeadersLodashMerge');
return arr;
}
//runs under both lodash and underscore - faster in underscore AFAICT
function addHeadersUnderscoreDefaults(arr, headers) {
//console.time('addHeadersUnderscoreDefaults');
var temp = _.pick(arr.shift(), headers);
arr.forEach(function(e, i, a) {
a[i] = _.defaults(e, temp);
});
//console.timeEnd('addHeadersUnderscoreDefaults');
return arr;
}
function addHeadersNewFunc(arr, headers) {
//console.time('addHeadersNewFunc');
var header = arr.shift(),
funcBody = ['return item;'],
headerPropName,
setProps;
for(var h = headers.length; h--;) {
headerPropName = headers[h];
funcBody.unshift('item["' + headerPropName + '"]="' + header[headerPropName] + '";'); //unshift since loop is reversed and we want props in same add order as other implementations, and we've already added our first line
}
setProps = new Function('item', funcBody.join('')); //warning, this is a form of 'eval()'...
for (var i = arr.length; i--;)
{
setProps(arr[i]);
}
//console.timeEnd('addHeadersNewFunc');
return arr;
}
function addHeadersLazy(arr, headers) {
//console.time('addHeadersLazy');
var lazy = new Lazy(arr, headers),
result = [];
for (var i = 1; i < arr.length; i++) {
result.push(lazy.get(i));
}
//console.timeEnd('addHeadersLazy');
return result;
}
function addHeadersLazyMemo(arr, headers) {
//console.time('addHeadersLazyMemo');
var lazy = new Lazy(arr, headers, true),
result = [];
for (var i = 1; i < arr.length; i++) {
result.push(lazy.get(i));
}
//console.timeEnd('addHeadersLazyMemo');
return result;
}
function Lazy(arr, headers, useMemo) {
var headerValSrc = arr[0],
headerLen = headers.length,
memo = [];
function _get(index) {
for (var j = 0; j < headerLen; j++) {
arr[index][headers[j]] = headerValSrc[headers[j]];
}
return arr[index];
}
function _getMemo(index) {
if (memo[index]) {
return memo[index];
}
for (var j = 0; j < headerLen; j++) {
arr[index][headers[j]] = headerValSrc[headers[j]];
}
return (memo[index] = arr[index]);
}
return {
get: (useMemo ? _getMemo : _get)
};
}
function clone(data) {
return JSON.parse(JSON.stringify(data));
}
function perfTest(name, testFunc) {
name = name ? name : "Test";
var iterations = 1000,
argsSliced = Array.prototype.slice.call(arguments, 2),
args = [],
t0 = 0,
t1,
t2,
t3,
tmin = 1000000,
tmax = 0,
output;
setTimeout(function delayAllowingDocWrite() {
for (var i = 0; i < iterations; i++) {
args = clone(argsSliced);
t1 = performance.now();
testFunc.apply(this, args);
t2 = performance.now();
t3 = t2 - t1;
tmin = t3 < tmin ? t3 : tmin;
tmax = t3 > tmax ? t3 : tmax;
t0 += t3;
}
output = name + " x " + iterations + ": [Avg] " + (t0 / iterations).toFixed(4) + "ms, [Min] " + tmin.toFixed(4) + "ms, [Max] " + tmax.toFixed(4) + "ms";
console.log(output);
document.body.innerHTML += (output + "<br />");
}, 10);
return testFunc.apply(this, clone(argsSliced)); //return output of function immed, once, for comparing results
}
document.body.innerHTML += "Items: " + arr.length + "<br />";
console.log("Items: ", arr.length);
//*
var resultOrig = perfTest("addHeadersOrig", addHeadersOrig, arr, headers),
resultDefineProp = perfTest("addHeadersDefineProp", addHeadersDefineProp, arr, headers),
resultStrReplace = perfTest("addHeadersStrReplace", addHeadersStrReplace, arr, headers),
//resultLodashMerge = perfTest("addHeadersLodashMerge", addHeadersLodashMerge, arr, headers), //re-enable if using lodash.min.js
resultUnderscoreDefaults = perfTest("addHeadersUnderscoreDefaults", addHeadersUnderscoreDefaults, arr, headers),
resultLazy = perfTest("addHeadersLazy", addHeadersLazy, arr, headers),
resultLazyMemo = perfTest("addHeadersLazyMemo", addHeadersLazyMemo, arr, headers),
resultNewFunc = perfTest("addHeadersNewFunc", addHeadersNewFunc, arr, headers);
//*/
var resultOrigStr = JSON.stringify(resultOrig),
outputIsConsistent = "Output of functions is all consistent: " + (
resultOrigStr === JSON.stringify(resultDefineProp) &&
resultOrigStr === JSON.stringify(resultStrReplace) &&
//resultOrigStr === JSON.stringify(resultLodashMerge) &&
resultOrigStr === JSON.stringify(resultUnderscoreDefaults) &&
resultOrigStr === JSON.stringify(resultLazy) &&
resultOrigStr === JSON.stringify(resultLazyMemo) &&
resultOrigStr === JSON.stringify(resultNewFunc)
);
document.body.innerHTML += outputIsConsistent + "<br /><em>Testing...</em><br /><br />";
console.log(outputIsConsistent);
if (!window.performance || !window.performance.now) {
document.body.innerHTML += "Your browser does not seem to support performance.now()...";
}
/*
var arr1 = clone(arr),
arr2 = clone(arr),
arr3 = clone(arr),
arr4 = clone(arr),
arr5 = clone(arr),
arr6 = clone(arr);
var resultOrig = addHeadersOrig(arr1, headers),
resultDefineProp = addHeadersDefineProp(arr2, headers),
resultStrReplace = addHeadersStrReplace(arr3, headers),
resultLodash = addHeadersLodash(arr4, headers),
resultLazy = addHeadersLazy(arr5, headers),
resultLazyMemo = addHeadersLazyMemo(arr6, headers);
console.log(resultOrig);
console.log(resultDefineProp);
console.log(resultStrReplace);
console.log(resultLodash);
console.log(resultLazy);
console.log(resultLazyMemo);
//*/
})();
body {
font-size: 0.8em;
font-family: "Arial", sans-serif;
}
<!--script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js"></script-->
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<p>Use a browser that supports performance.now().</p>
For easier playing around with: Plnkr

Comparing two arrays and push in another array wrong position element

I got two arrays, both type string :
var correctAnswers = ["0", "1", "2", "3", "4", "5"];
and second :
var finalArray = ["0", "1", "4", "3", "5", "2"];
I would like to compare them and and if not match second with first to extract elements and push them in another array, like this :
finalArray = ["0", "1", "3"];
var toChange = ["4", "5", "2"];
You could use jQuery map method too:
var toChange = $.map(finalArray, function(v, k){
return correctAnswers[k] !== v ? v: null;
});
finalArray = $.map(finalArray, function(v, k){
return correctAnswers[k] === v ? v: null;
});
DEMO
Or using array.prototype.filter():
var toChange = finalArray.filter(function(v, k){
return correctAnswers[k] !== v;
});
finalArray = finalArray.filter(function(v, k){
return correctAnswers[k] === v;
});
filter DEMO
var toChange = [];
for (var i = finalArray.length - 1; i >= 0; i--) {
if (finalArray[i] !== correctAnswers[i]) {
toChange.push(finalArray[i]);
finalArray.splice(i, 1);
}
}
The key to this is iterating down from the length to 0, rather than up from 0 to the length as usual. This is because splice changes the indexes of all the elements after the element being removed, so normal iteration would skip an element after each splice.
This will do it:
http://jsfiddle.net/XiozZe/NkM6s/
var correctAnswers = ["0", "1", "2", "3", "4", "5"];
var finalArray = ["0", "1", "4", "3", "5", "2"];
var correctFinal = [];
var toChange = [];
for(var i = 0; i < correctAnswers.length; i++){
if(correctAnswers[i] === finalArray[i]){
correctFinal[correctFinal.length] = finalArray[i];
}
else{
toChange[toChange.length] = finalArray[i];
}
}
First you've got to define your variables
// Define your variables
var correctAnswers = ["0", "1", "2", "3", "4", "5"];
var answers = ["0", "1", "4", "3", "5", "2"];
var finalArray = [];
var toChange = [];
Then you create a loop, which loops over the Answers array.
// comparing them could be done with a simple loop
for (var i = 0; i<answers.length; i++) {
if (correctAnswers[i] == answers[i]) { //if they're equal, push the value into the final array
finalArray.push(answers[i]);
} else { // if not, push them into the toChange array
toChange.push(answers[i]);
}
}
This will give you toChange = [0, 1, 3]
If you want toChange = [0, 1] you've got to change it to
toChange = answers.slice(0);
for (var i = 0; i<correctAnswers.length; i++) {
if (correctAnswers[i] == Answers[i]) { //if they're equal, push the value into the final array and remove the first value from the toChange array
finalArray.push(Answers[i]);
toChange.shift();
} else { // if not, break
break;
}
}
Fiddle

Categories

Resources