finding index of duplicates in an array in js - javascript

I have two arrays
arr1=[ 0, 1, 2, 0, 2 ];
arr2=[ 0, 0, 1, 2, 2 ];
I have to find index of elements of arr2 from arr1 and output array need to be like [0,3,1,2,4];
I have written a code but it works on array without duplicate`
var index = [];
for (i = 0; i <= arr2.length - 1; i++) {
index.push(arr1.indexOf(arr2[i]));
}

You need to search after the first index for the second element and same for all repeating elements(for third after index). You can specify fromIndex argument in Array#indexOf method to start the search at a specific index.
// use a reference object to specify from index for duplicate
var ref = {};
var index = [];
for (i = 0; i < arr2.length; i++) {
// specify from index from object, if not found set as 0
var i1 = arr1.indexOf(arr2[i], ref[arr2[i]] || 0);
// push the index
index.push(i1);
// specify from index for current element
ref[arr2[i]] = i1 + 1;
}
var ref = {};
var arr1 = [0, 1, 2, 0, 2],
arr2 = [0, 0, 1, 2, 2];
var ref = {};
var index = [];
for (i = 0; i < arr2.length; i++) {
var i1 = arr1.indexOf(arr2[i], ref[arr2[i]] || 0);
index.push(i1);
ref[arr2[i]] = i1 + 1;
}
console.log(index);
Using Array#map method to generate the index array.
var index = arr2.map(function(v, i) {
// get the index of the element, where specify from index to
// search after a certain index for repeating element
var i1 = arr1.indexOf(v, this[v] || 0);
// set reference of index
this[v] = i1 + 1;
// return index
return i1;
// set this argument as an object for from index reference
}, {});
var arr1 = [0, 1, 2, 0, 2],
arr2 = [0, 0, 1, 2, 2];
var index = arr2.map(function(v, i) {
var i1 = arr1.indexOf(v, this[v] || 0);
this[v] = i1 + 1;
return i1;
}, {});
console.log(index);

var arr1 = [ 0, 1, 2, 0, 2 ];
var arr2 = [ 0, 0, 1, 2, 2 ]
var index = [];
var hash = {};
for (i = 0; i < arr2.length; i++) {
var ind_temp;
if(arr2[i] in hash){
//console.log("here");
ind_temp = arr1.indexOf(arr2[i],hash[arr2[i]] + 1);
index.push(ind_temp);
hash[arr2[i]] = ind_temp;
}
else{
ind_temp = arr1.indexOf(arr2[i]);
index.push(ind_temp);
hash[arr2[i]] = ind_temp;
}
}
console.log(index);

You can look through the array and map it onto anther array, setting the first instance to undefined. Obviously this doesnt work if undefined is a value you could want to search for.
var zz = arr1.map(val => {
if (!val) return undefined
let ind = arr2.indexOf(val)
if (ind) arr2[ind] = undefined
return ind
})

If you have just positive numbers, try this
var temp = arr1.slice(0); //Clone arr1 to a temp Arr
var index = [];
arr2.forEach(item => {
let ind = temp.indexOf(item);
index.push(ind);
ind > -1 && (temp[ind] = -1);
})
console.log(index);

What you can do is iterate over arr2 and save found index from arr1 in variable, and if element of arr2 is equal to previous element in arr2 then compare from saved index + 1, for this you can use 2nd parameter of indexOf method.
var duplicate =[ 0, 1, 2, 0, 2 ];
var newiter =[ 0, 0, 1, 2, 2 ];
var indexArray = []; //RESULT ARRAY
var newiter = newiter.sort(); //IN CASE newiter IS NOT SORTED
var i = -1;
for(var j = 0; j<newiter.length; j++) {
// check if element from newiter is equal to previous , if not set i to -1
if(j > 0 && newiter[j] != newiter[j-1]) {
i = -1;
}
// get index from duplicate but start searching from i+1
i = duplicate.indexOf(newiter[j], i+1);
indexArray.push(i);
}
console.log(indexArray);

Related

code check :i expect IndexPlus is 2 but it seems it becom 1+1=11,why?

description :
i expect the indexPlus 2 but it comes 11,what is wrong? and why?
see it in line 28 .
code:
var inputArr = [1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0]
console.log('before', inputArr)
var arr = []
//先遍历inputArr确定0的位置
for (key in inputArr) {
if (inputArr[key] === 0) {
arr.push(key)
}
}
//将0移到数组最后面,通过位置交换实现
for (value of arr) {
for (i = value; i < inputArr.length - 1; i++) {
swap(i, i + 1)
}
}
function swap(index, indexPlus) {
var temp = inputArr[index]
inputArr[index] = inputArr[indexPlus]
inputArr[indexPlus] = temp
}
console.log('after', inputArr)
When you do for (key in inputArr), the keys are strings, not integers. So later when you do swap(i, i + 1), i is a string, and i + 1 does string concatenation, not integer addition.
Change the first loop to loop over indexes, not keys.
var inputArr = [1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0]
console.log('before', inputArr)
var arr = []
//先遍历inputArr确定0的位置
for (let key = 0; key < inputArr.length; key++) {
if (inputArr[key] === 0) {
arr.push(key)
}
}
//将0移到数组最后面,通过位置交换实现
for (value of arr) {
for (i = value; i < inputArr.length - 1; i++) {
swap(i, i + 1)
}
}
function swap(index, indexPlus) {
var temp = inputArr[index]
inputArr[index] = inputArr[indexPlus]
inputArr[indexPlus] = temp
}
console.log('after', inputArr)
When you use for ( in ), in every single loop, you will get a key(position) as a string. So when you take it and + 1 you will get result as a string.

Why this Javascript quicksort method only return one character in an array

var arr = [4, 5, 6, 3, 4, 5, 2, 5, 6, 4, 2,];
function quickSort(arra) {
if (arra.length <= 1) {
return arra;
}
else {
var len = arra.length;
var left = [];
var right = [];
var temp = arra.pop();
var newarr = [];
for (var i = 1; i < len; i++) {
if (arra[i] < temp) {
left.push(arra[i]);
}
else { right.push[i]; }
}
}
return newarr.concat(quickSort(left), temp, quickSort(right));
}
console.log(quickSort(arr))
The result is:
I wonder why this method only return me one character in the array?
pop() method removes last element from array (so length decreases by 1) and first element has index 0 so you need to replace your for loop with:
for (var i = 0; i < len-1; i++) {
Also you need to change right.push[i] as mentioned in comments.

Get small element index till array length

I have to sort an array and want to get index so that I can sort another array on the basis of this index..
There are two array a and b I saved division of that array in third array that is sortDiv now I want index of small element so that I can sort a and b according to index..
Code is like
var a = [6, 7, 8, 9];
var b = [1, 2, 3, 4];
var sortA = [],
sortB = [],
sortDiv = [];
var div = a[0] / b[0];
for (var i = 0; i < a.length; i++) {
sortDiv.push(a[i] / b[i]);
}
var temp = sortDiv;
for (var i = 1; i < sortDiv.length; i++) {
var val = Math.min.apply(Math, temp);
var key = sortDiv.indexOf(val);
sortA.push(a[key]);
sortB.push(b[key]);
if (key > -1)
temp.splice(key, 1);
}
console.log(sortA + " " + sortB);
I got [9,8] for a and [4,3] for b..while I want a=[9,8,7,6] b=[1,2,3,4]
But splice is not a good option..I need a function that remove only element not an index..any idea please?
UPDATED
As problem is solved but I want to know that
Is it possible to remove element but not an index in array?
Try not removing element just replacing it with maximum element +1 and it will work fine here is the updated code
var a = [6, 7, 8, 9];
var b = [1, 2, 3, 4];
var sortA = [],
sortB = [],
sortDiv = [];
var div = a[0] / b[0];
for (var i = 0; i < a.length; i++) {
sortDiv.push(a[i] / b[i]);
}
console.log(sortDiv);
var temp = sortDiv;
var max = Math.max.apply(Math, temp); // here we find the maximum
max += 1;
for (var i = 1; i <= sortDiv.length; i++) {
var val = Math.min.apply(Math, temp);
console.log(val);
var key = sortDiv.indexOf(val);
sortA.push(a[key]);
sortB.push(b[key]);
temp[key] = max; // here we update the minimum with maximum+1
}
console.log(sortA + " " + sortB);
If the question is about using splice to remove an item based on the value and not the index, get the index, then use splice:
var a = ['a', 'b', 'c'];
a.splice(a.indexOf('b'), 1);
console.log(a); // ["a", "c"]

Java Script - Adding null value to array, if the element is not present at particular index

Array length is 7
Original array
var arr = [2, 4, 6];
Needed array
arr = [null,null,2,null,4,null,6];
0 is not present in array so need to replace with null,
1 is not available replace with null and
2 is available so put 2 in new array so on..
You can use the splice() method on the array
var arr=[2,4,6];
var l = arr[arr.length-1];
for(var i=0; i<=l; i++){
if(arr[i] !== i){
arr.splice(i, 0, null);
}
}
Output : [null, null, 2, null, 4, null, 6]
This modifies the original array.
I will write a permanence case for all answers soon.
function createArrayFromArray(array, length) {
var new_array = new Array(length);
for (var i = 0; i < new_array.length; i++) {
new_array[i] = null;
}
for (var i = 0; i < array.length; i++) {
new_array[array[i]] = array[i];
}
return new_array;
}
console.log(createArrayFromArray(arr, 7)); //[null, null, 2, null, 4, null, 6]
You just need to find the max value in the array and then iterate from 0 to that max, checking each value to see if it was present in the source or not:
var arr = [2, 4, 6];
var max = Math.max.apply(Math, arr);
var result = [];
for (var i = 0; i <= max; i++) {
if (arr.indexOf(i) !== -1) {
result[i] = i;
} else {
result[i] = null;
}
}
Working demo: http://jsfiddle.net/jfriend00/c7p8mkqy/
As I asked in my comments, I'd like to know what problem you're actually trying to solve because it seems like both the original and the newly created data structures are inefficient structures that could probably use different form of data and work more efficiently. But, we can only help you make a wiser choice if you explain the actual problem, rather just your attempted solution.
Given you have the only input arr which you want to fill null inside. Try this:
var arr = [2, 4, 6];
var output = [];
while (arr.length>0){
var first = arr.splice(0,1);
while (output.length<first[0])
output.push(null);
output.push(first[0]);
}
// output should be [null,null,2,null,4,null,6];
Try:
var arr = [2, 4, 6];
var new_arr = [];
var i = 0;
while(i < 7){
var pos = arr.indexOf(i++);
new_arr.push(pos !== -1 ? arr[pos] : null)
}
document.write(JSON.stringify(new_arr, null, 4))
var arr = [2, 4, 6];
var result = new Array(7);
arr.forEach(function(a) { result[a] = a;});
Interesting quiz:
var arr = [2, 4, 6]
var n = 0
while(arr.length > n) {
if(arr[n] !== n) {
arr = arr.slice(0,n).concat(null, arr.slice(n))
}
n++
}
console.log(arr) // [null, null, 2, null, 4, null, 6]
This approach applies to array consists of random number of sorted integers.
var arr = [2, 4, 6];
var narr = (new Array(arr.sort()[arr.length-1]))
arr.map(function(v){
narr[v] = v;
});
for (var i = 0; i<narr.length; i++) narr[i]||(narr[i]=null);
console.log(narr);
Try splice():
var arr = [2, 4, 6];
var i = 0,
l = arr[arr.length - 1];
while (i < l) {
if(i !== arr[i])
arr.splice(i, 0, null);
i++;
}
console.log(arr); //[ null, null, 2, null, 4, null, 6 ]

Moving several elements within array to a certain index in array

I have an array of elements.
0,1,2,3,4,5,6,7,8,9
user can pick any number of elements and ask to move them after any 1 particular element.
example: ask for 4,5,7 to be moved after 1 for example, thus resulting in
0,1,4,5,7,2,3,6,8,9
or ask for 0,5 to be moved after 9
1,2,3,4,6,7,8,9,0,5
any pseudo code is greatly appreciated.
move_after= function(after, move_array) {
//remove elements from the array
move_array.forEach(function(element) {
var index = operations.indexOf(element);
operations.splice(index, 1);
});
var after_index = operations.indexOf(after) + 1;
//insert each move_array element to array
move_array.forEach(function(element) {
operations.splice(after_index++, 0, element);
});
}
move_after(2, [0,1]);
doesn't exactly give me what i want
Here a prototype is used, which inserts an array into an array after a specific digit:
Array.prototype.insertIntoArr = function(insert, digit) {
var i = this.indexOf(digit) + 1;
return this.slice(0, i).concat(insert).concat(this.slice(i));
}
The function moveAfter( ... ) first cleans the array from the values of toMove. Second toMove is inserted after the specific digit:
function moveAfter(arr, toMove, after) {
toMove.forEach(function (value) {
arr.splice(arr.indexOf(value), 1);
});
var res = arr.insertIntoArr(toMove, after);
return res;
}
Example
What about something like this: http://plnkr.co/edit/k2h6BWTUCFj5BS4oFF8C
(function(){
var arr = [0,1,2,3,4,5,6,7,8,9];
var userArr = [4,5,7];
var temp = [];
var pos = 1;
for(var i = arr.length; i >= 0; i--){
if(userArr.indexOf(arr[i]) !== -1){
temp.push(arr[i]);
arr.splice(i, 1);
}
}
for(var i = 0; i < temp.length; i++){
arr.splice(arr.indexOf(pos) + 1, 0, temp[i]);
}
console.log(arr);
//outputs [0, 1, 4, 5, 7, 2, 3, 6, 8, 9]
})();
Using your idea
function move_after(orig_array, after, move_array) {
//remove elements from the array
move_array.forEach(function(element) {
var index = operations.indexOf(element);
orig_array.splice(index, 1);
});
var after_index = orig_array.indexOf(after) + 1;
//insert each move_array element to array
move_array.forEach(function(element) {
orig_array.splice(after_index++, 0, element);
});
return orig_array;
}
Then you use
var result = move_after([0, 1, 2] , 2, [0,1]);
Hope it works,
Dan
Try this:
move_after = function (after, move_array) {
var i, s;
s = [];
for (i = 0; i < 10; i++)
{
// only append "i" it if is NOT in move_array
if (move_array.indexOf(i) === -1) s.push(i);
if (i == after) s.push(move_array);
}
return s;
};
Something like this?
var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var b = move_after(1, [4, 5, 7]);
var c = move_after(9, [0, 5]);
console.log(a);
console.log(b);
console.log(c);
function move_after(moveAfter, toMove) {
var arr = a.reduce(function (c, e, i) {
if (toMove.indexOf(e) === -1) {
c.push(e);
}
return c;
}, []);
var toMoveAfterIndex = arr.indexOf(moveAfter) + 1;
Array.prototype.splice.apply(
arr, [toMoveAfterIndex, 0].concat(toMove)
);
return arr;
}

Categories