Javascript array match with less complexity -
for example
inputarray = [1, 4, 5, 9]; array1 = [1, 2, 3, 4, 5, 6, 7]; array2 = [8, 9, 10, 11, 12, 13, 14];
i match inputarray both array1 & array2.in current scenario 1,4,5 belongs array1 , 9 belongs second array.i expecting output
outputarray1=[1,4,5] outputarray2=[9]
suggest me best way problem.i mean less complexity.thanks in advance.
at cost of space, can make hash objects , have constant time lookups contains instead of using o(n) indexof
calls or loops:
var inputarray = [1, 4, 5, 9]; var array1 = [1, 2, 3, 4, 5, 6, 7]; var array2 = [8, 9, 10, 11, 12, 13, 14]; var array1hash = object.create(null); var array2hash = object.create(null); var outputarray1 = []; var outputarray2 = []; array1.foreach(function(e) { array1hash[e] = true; }); array2.foreach(function(e) { array2hash[e] = true; }); inputarray.foreach(function(e) { if (e in array1hash) { outputarray1.push(e); } if (e in array2hash) { outputarray2.push(e); } }); document.getelementbyid('out1').innerhtml = json.stringify(outputarray1); document.getelementbyid('out2').innerhtml = json.stringify(outputarray2);
<pre id="out1"></pre> <pre id="out2"></pre>
Comments
Post a Comment