Push value into array of arrays in JavaScript - javascript

I have and array of arrays which looks like this:
var arr = [[1,2,3],[4,5,6],[7,8,9]];
After that I have a list of numbers and a loop
var list = [15,10,11,14,13,12]
for (i=0; i<list.length; i++) {
var val = list[i];
if (val >= 10 && val < 13) {
arr[arr.length].push(val);
}
else if (val >= 13 && val < 16) {
arr[arr.length+1].push(val);
}
}
So basically I like to have an output which will look like this:
arr = [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]];
With this code I'm getting an error "Cannot read property 'push' of undefined"
Also important is I can't use arr[3].push or arr[4].push because my case is more complicated and always I need to push values to new array which will appear on the over of my array. No matter how many objects I have inside.

This is happening because arr[arr.length] will always be undefined.
So you're basically doing
undefined.push(x);
// Cannot read property 'push' of undefined
"Also important is I can't use arr[3].push or arr[4].push because my case is more complicated and always I need to push values to new array which will appear on the over of my array. No matter how many objects I have inside."
This algorithm is a code smell tho and we could probably help you better if you post your actual code.
To see what I'm talking about, consider the following code
// your numbers in a random order
var xs = [7,10,2,15,4,9,14,1,8,12,5,11,3,6,13];
// sort them
xs.sort(function(a, b) { return a-b; });
// define a function that "chunks" a list into smaller parts
function chunk(xs, n) {
function iter(ys, y, xs) {
if (y.length === 0) return ys;
return next(ys.concat([y]), xs);
}
function next(ys, xs) {
return iter(ys, xs.slice(0,n), xs.slice(n));
}
return next([], xs);
}
// call our function on your sorted list
var ys = chunk(xs, 3);
console.log(JSON.stringify(ys));
//=> [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]]

arr[arr.length] can never return any meaningful, think about it: if you have an array of length 6, then you have indexes 0..5 to work with.
arr[6] will always return undefined because there's nothing there.
You probably need something like this:
if (val >= 10 && val < 13) {
arr[arr.length - 1].push(val);
}
else if (val >= 13 && val < 16) {
arr[arr.length].push([val]);
}

If you are looking sort the array element then your code will not work. Refer below code to sort the element and it will also solve your undefined issue.
<script>
var arr = [[1,2,3],[4,5,6],[7,8,9]];
var list = [15,10,11,14,13,12];
var arr1=[];
var arr2=[];
for (i=0; i<list.length; i++) {
var val = list[i];
if (val >= 10 && val < 13) {
arr1.push(val);
}
else if (val >= 13 && val < 16) {
arr2.push(val);
}
}
arr1.sort(function(a, b){return a-b});
arr.push(arr1);
arr2.sort(function(a, b){return a-b});
arr.push(arr2);
console.log(arr);
</script>

You need something like this:
var arr = [[1,2,3],[4,5,6],[7,8,9]];
var list = [15,10,11,14,13,12];
for (var i=0; i<list.length; i++) {
var val = list[i];
var index = Math.floor((val-1)/3);
if ( arr[index] === undefined )
arr[index] = [];
arr[index].push(val);
arr[index].sort();
}
console.log( arr );

Related

Replacing localStorage with new values

I am reading the values from localStorage as nested array and based on some conditions, I am deleting few arrays from the read array. To delete the arrays from master array, I am using the following function:
Array.prototype.diff = function(a) {
return this.filter(function(i) {return a.indexOf(i) < 0;});
};
The resultant array is smaller than the original nested array. The following is my original array from localStorage:
var arr = `"["STAR_SPORTS_2-20170924-200043-210917-00142.jpg","PerimeterBoard","Gillette",270,399,387,397,390,472,"STAR_SPORTS_2-20170924-200043-210917-00142.jpg","PerimeterBoard","Gillette",270,399,387,397,390,472,"STAR_SPORTS_2-20170924-200043-210917-00142.jpg","PerimeterBoard","Gillette",321,322,414,333,418,375]"`
//Function to drop rectangles
function dropRects() {
dragging = false;
mLocation = getCanvasCoordinates(event);
var a = Math.floor(mLocation.x);
var b = Math.floor(mLocation.y);
var clickedImg = localStorage.getItem('clickedImage');
var arr = new Array();
var getCoords = getArray();
if (typeof getCoords !== 'undefined' && getCoords.length > 0) {
var allCoords = fourthCoord(getCoords);
arr = multiDimensionalUnique(allCoords);
the example array arr given above is the result of `multiDimensionalUnique(allCoords);
var results = new Array();
//For each item in array, perform calculation to find the array that needs to be deleted and store the found array in results - This is working properly
arr.forEach(function(d) {
if (d[0] === clickedImg && d[3] < a && d[4] < b && d[5] > a && d[6] < b && d[7] > a && d[8] > b && d[9] < a && d[10] > b) {
results.push(d)
}
});
//delete the found array from master array.
var newArr;
newArr = arr.diff(results);
//Delete the empty array [] from the master array
var secArr;
secArr = newArr.filter(function(x) { return (x !== (undefined || null || ''));})
//Delete the last two elements from each array, so that it is exactly the same as array downloaded from localStorage
for (var i = 0;i < secArr.length; i++) {
secArr[i].splice(9,2);
}
secArr = JSON.stringify(secArr)
console.log(secArr);
}
localStorage.setItem('coords', secArr);
}
The console.log(secArr) prints the following result (new array):
[["STAR_SPORTS_2-20170924-200043-210917-00142.jpg","PerimeterBoard","FBB",270,406,377,396,381,469],["STAR_SPORTS_2-20170924-200043-210917-00142.jpg","PerimeterBoard","Gillette",326,321,425,332,420,375],["STAR_SPORTS_2-20170924-200043-210917-00143.jpg","PerimeterBoard","Gillette",367,323,492,330,492,378]]
I am not sure why I have an extra square bracket at the beginning and at the end of this array. (pardon me if this result is different from the example data given above, as this is from my live dashboard)
And the line localStorage.setItem('coords', secArr) resets the localStorage with the new values which looks like this:
"[["STAR_SPORTS_2-20170924-200043-210917-00142.jpg","PerimeterBoard","FBB",270,406,377,396,381,469],["STAR_SPORTS_2-20170924-200043-210917-00142.jpg","PerimeterBoard","Gillette",326,321,425,332,420,375],["STAR_SPORTS_2-20170924-200043-210917-00143.jpg","PerimeterBoard","Gillette",367,323,492,330,492,378]]"
again with preceeding and succeeding square brackets.
Since the new array is nested within another array, when I read the localStorage again, I am not able to retrieve the array. How do I post secArr variable into localStorage as my original coords variable.
I suspect your answer is due to the double quotes in the var arr declaration. Please look at the following code:
arr = ["STAR_SPORTS_2-20170924-200043-210917-00142.jpg","PerimeterBoard","Gillette",270,399,387,397,390,472,"STAR_SPORTS_2-20170924-200043-210917-00142.jpg","PerimeterBoard","Gillette",270,399,387,397,390,472,"STAR_SPORTS_2-20170924-200043-210917-00142.jpg","PerimeterBoard","Gillette",321,322,414,333,418,375];
Array.prototype.diff = function(a) {
return this.filter(function(i) {return a.indexOf(i) < 0;});
};
clickedImg = true;
var results = new Array();
//For each item in array, perform calculation to find the array that needs to be deleted and store the found array in results - This is working properly
arr.forEach(function(d) {
if (d[0] === clickedImg && d[3] < a && d[4] < b && d[5] > a && d[6] < b && d[7] > a && d[8] > b && d[9] < a && d[10] > b) {
results.push(d)
}
});
//delete the found array from master array.
var newArr;
newArr = arr.diff(results);
//Delete the empty array [] from the master array
var secArr;
secArr = newArr.filter(function(x) { return (x !== (undefined || null || ''));})
//Delete the last two elements from each array, so that it is exactly the same as array downloaded from localStorage
for (var i = 0;i < secArr.length; i++) {
secArr[i].splice(9,2);
}
secArr = JSON.stringify(secArr)
console.log(secArr);
It produces
["STAR_SPORTS_2-20170924-200043-210917-00142.jpg","PerimeterBoard","FBB",270,406,377,396,381,469],["STAR_SPORTS_2-20170924-200043-210917-00142.jpg","PerimeterBoard","Gillette",326,321,425,332,420,375],["STAR_SPORTS_2-20170924-200043-210917-00143.jpg","PerimeterBoard","Gillette",367,323,492,330,492,378] (notice no array within array).

javascript check if array contains multiple elements in a row

I would like to know if its possible to search an array for multiple items which are in a row, something similar to below. I have done it with separate includes, but this does not allow me to tell if the elements are in a row or near each other.
The array is not sorted and the numbers have to be in a defined order. Near being in a row, specifically 3. So (23,34,45) being searched within (12,23,45,34) would be false.
Thanks
var num = [];
num.push(12,23,34,45,56,67,78,89,90);
if(num.includes(23,34,45)){
print('found');
}
One more way using ES6 Set() feature:
var arr = [12,23,34,12,45,56,67,78,89,90];
var set = new Set();
arr.forEach(function(i){ set.add(i) });
var foundCount = 0;
var func = function(a){
a.forEach(function(item) {
var oldLength = set.size;
set.add(item);
var newLength = set.size;
if(oldLength === newLength) {
foundCount++;
}
});
console.log('found ' + foundCount)
}
var arr2 = [12, 34, 45];
func(arr2);
This works, I hope I understood your question correctly.
function foo(num1, num2, num3, arr) {
var exists = false;
for(var i = 0; i < arr.length; i++) {
if(arr[i] == num1 && arr[i+1] == num2 && arr[i+2] == num3) {
exists = true;
}
}
console.log(exists);
}
var array = [12,23,34,45,56,67,78,89,90];
foo(23,34,45,array);

Javascript array return is adding double quotes?

Here is my code:
function iLoveThree (array) {
var threes = [];
var x;
for (x in array) {
if (x % 3 == 0) {
threes.push(x)
}
}
return threes
}
When I pass the array [1,2,3,4,5,6,7,8,9] I get the following:
Function returned
["0","3","6"]
instead of
[3,6,9]
My question is, where are these double quotes coming from?
for...in is a bad way of iterating array indices. Better use filter:
[1,2,3,4,5,6,7,8,9].filter(function(x) {
return x % 3 == 0;
}); // [3, 6, 9]
A for..in loop does not loop through the array elements, it loops through the indices of the array. So for:
var arr = ["a", "b", "c"]
for ( x in arr ) console.log( x );
You'll get the string keys of ["0", "1", "2"]
You can fix your code by replacing your loop with a native for loop:
for ( var x = 0; x < array.length; x++ ) {
if (array[i] % 3 == 0)
threes.push(array[i]);
}
So basically in x in array x is the index not the array value. Because anyway 0 is not in the array but your function is returning it as well. You should instead access the values using array[x]
There are various approaches, one of them is using .filter
function iLoveThree(array){
return array.filter(function(x){
return (x%3==0?1:0);
});
}
Or
function iLoveThree (array) {
var threes = [];
var x;
[].forEach.call(array, function(x){
if (x % 3 == 0) {
threes.push(x)
}
}
return threes
}
You're using a for..in loop which gives you the keys in an object, or in this case and array. Keys are always strings. Instead, you want to use a standard for loop.
for (var i = 0; i < array.length; i++) {
var x = array[i];
if (x % 3 === 0) {
threes.push(x);
}
}
Or if you want to use a more functional approach, you could use Array.prototype.filter.
return array.filter(function(x) {
return x % 3 === 0;
});
Not an answer to your question directly, but here's a nice way to pull every multiple of 3 from an array of numbers:
[1,2,3,4,5,6,7,8,9].filter(item => item % 3 === 0)
It seems that you are pushing in the indexes and not the actual values, go ahead and try the following:
function iLoveThree(array) {
var threes = [];
var x;
for (x in array) {
if (((x-2) % 3) == 0) {
threes.push(array[x])
}
}
return threes;
}
Another option, shorter, is:
function iLoveThree(arr) {
var threes = [];
for (var i = 2; i < arr.length; i = i + 3) {
threes.push(arr[i]);
};
return threes;
}
if you are comfortable with callback/predicate based loops, you could make stuff even shorter by filtering the array, instead of creating a new one:
function iLoveThree(arr) {
return arr.filter(function(x) {
return (x % 3) == 0;
});
}
Before you read the answer below, please read: Why is using “for…in” with array iteration such a bad idea? (Thanks to #Oriol for this link.)
Douglas Crockford has also discouraged the use of for..in. He recommends using array.forEach instead.
function iLoveThree (array) {
var threes = [];
array.forEach(function(item, i){ // use forEach, 'item' is the actual value and 'i' is the index
if (item % 3 === 0) {
threes.push(item); // you missed ; here
}
});
return threes; // you missed ; here
}
console.log(iLoveThree([1,2,3,4,5,6,7,8,9]));
Read up: Array.prototype.forEach() | MDN
If you read the for...in documentation, you will realize that you are pushing to threes the indexes (also called keys) not the values, because the variable x represents the index, so the value should be accessed by array[x].
function iLoveThree (array) {
var threes = [];
for (var x in array) {
if (array[x] % 3 == 0) {
threes.push(array[x])
}
}
return threes
}
There are several ways to achieve this, the best one is by using a filter, but that way was already explained by someone else, therefore I will use an exotic implementation using a reduce
[1, 2, 3, 4, 5, 6, 7, 8, 9].reduce(function(acc, e){return e % 3 == 0 ? acc.concat(e) : acc}, [])
Outputs 3, 6, 9

JavaScript: How to match out-of-order arrays

I'm trying to work out how to match arrays that share the same elements, but not necessarily in the same order.
For example, these two arrays share the same set of elements, even though they're in a different order.
Is there any way to determine whether two arrays contain the same elements?
var search1 = ["barry", "beth", "debbie"];
var search2 = ["beth", "barry", "debbie"];
if (search1 == search2) {
document.write("We've found a match!");
} else {
document.write("Nothing matches");
}
I've got a Codepen of this running at the moment over here: http://codepen.io/realph/pen/grblI
The problem with some of the other solutions is that they are of O(n²) complexity, if they're using a for loop inside of a for loop. That's slow! You don't need to sort either—also slow.
We can speed this up to O(2n) complexity1 by using a simple dictionary. This adds O(2n) storage, but that hardly matters.
JavaScript
var isEqual = function (arr1, arr2) {
if (arr1.length !== arr2.length) {
return false; // no point in wasting time if they are of different lengths
} else {
var holder = {}, i = 0, l = arr2.length;
// holder is our dictionary
arr1.forEach(function (d) {
holder[d] = true; // put each item in arr1 into the dictionary
})
for (; i < l; i++) { // run through the second array
if (!(arr2[i] in holder)) return false;
// if it's not in the dictionary, return false
}
return true; // otherwise, return true
}
}
Test Case
var arr1 = ["barry", "beth", "debbie"],
arr2 = ["beth", "barry", "debbie"];
console.log(isEqual(arr1,arr2));
// returns true
fiddle
Improvement
As Ahruss pointed out, the above function will return true for two arrays that are seemingly equal. For example, [1,1,2,3] and [1,2,2,3] would return true. To overcome this, simply use a counter in the dictionary. This works because !undefined and !0 both return true.
var isReallyEqual = function (arr1, arr2) {
if (arr1.length !== arr2.length) {
return false; // no point in wasting time if they are of different lengths
} else {
var holder = {}, i = 0, l = arr2.length;
// holder is our dictionary
arr1.forEach(function (d) {
holder[d] = (holder[d] || 0) + 1;
// checks whether holder[d] is in the dictionary: holder[d] || 0
// this basically forces a cast to 0 if holder[d] === undefined
// then increments the value
})
for (; i < l; i++) { // run through the second array
if (!holder[arr2[i]]) { // if it's not "in" the dictionary
return false; // return false
// this works because holder[arr2[i]] can be either
// undefined or 0 (or a number > 0)
// if it's not there at all, this will correctly return false
// if it's 0 and there should be another one
// (first array has the element twice, second array has it once)
// it will also return false
} else {
holder[arr2[i]] -= 1; // otherwise decrement the counter
}
}
return true;
// all good, so return true
}
}
Test Case
var arr1 = [1, 1, 2],
arr2 = [1, 2, 2];
isEqual(arr1, arr2); // returns true
isReallyEqual(arr1, arr2); // returns false;
1: It's really O(n+m) complexity, whereby n is the size of the first array and m of the second array. However, in theory, m === n, if the arrays are equal, or the difference is nominal as n -> ∞, so it can be said to be of O(2n) complexity. If you're feeling really pedantic, you can say it's of O(n), or linear, complexity.
you can use this function to compare two arrays
function getMatch(a, b) {
for ( var i = 0; i < a.length; i++ ) {
for ( var e = 0; e < b.length; e++ ) {
if ( a[i] === b[e] ){
return true;
}
}
}
}
Feed your arrays to the following function:
function isArrayEqual(firstArray, secondArray) {
if (firstArray === secondArray) return true;
if (firstArray == null || secondArray == null) return false;
if (firstArray.length != secondArray.length) return false;
// optional - sort the arrays
// firstArray.sort();
// secondArray.sort();
for (var i = 0; i < firstArray.length; ++i) {
if (firstArray[i] !== secondArray[i]) return false;
}
return true;
}
Now you may be thinking, can't I just say arrayOne.sort() and arrayTwo.sort() then compare if arrayOne == arrayTwo? The answer is no you can't in your case. While their contents may be the same, they're not the same object (comparison by reference).
You need to simply sort them, then compare them
function compareArrayItems(array1, array2){
array1 = array1.sort();
array2 = array2.sort();
return array1.equals(array2);
}
fiddle
You can use the equals function provided in How to compare arrays in JavaScript?
Sort them firstly. Secondly, if their length is different, then they're not a match.
After that, iterate one array and test a[i] with b[i], a being the first array, b the second.
var search1 = ["barry", "beth", "debbie"],
search2 = ["beth", "barry", "debbie"];
// If length are different, than we have no match.
if ((search1.length != search2.length) || (search1 == null || search2 == null))
document.write("Nothing matches");
var a = search1.sort(),
b = search2.sort(),
areEqual = true;
for (var i = 0; i < a.length; i++) {
// if any two values from the two arrays are different, than we have no match.
if (a[i] != b[i]) {
areEqual = false;
break; // no need to continue
}
}
document.write(areEqual ? "We've found a match!" : "Nothing matches");

deleting duplicates on sorted array

Just in case you missed, the question is about deleting duplicates on a sorted array. Which can be applied very fast algorithms (compared to unsorted arrays) to remove duplicates.
You can skip this if you already know how deleting duplicates on SORTED arrays work
Example:
var out=[];
for(var i=0,len=arr.length-1;i<len;i++){
if(arr[i]!==arr[i+1]){
out.push(arr[i]);
}
}
out.push(arr[i]);
See?, it is very fast. I will try to explain what just happened.
The sorted arrays *could look like this:
arr=[0,1,1,2,2,3,4,5,5,6,7,7,8,9,9,9];
*the sorting could be ASC or DESC, or by other weird methods, but the important thing is that every duplicated item is next each other.
We stopped at array.length-1 because we don't have anything to check with
Then we added the last element regardless of anything because:
case A:
... ,9,9,9];//we have dup(s) on the left of the last element
case B:
... ,7,9,10];//we don't have dup(s) on the left of the last element
If you really understand what is happening, you will know that we haven't added any 9 on the case A. So because of that, we want to add the last element no matter if we are on case A or B.
Question:
That explained, I want to do the same, but ignoring the undefined value on cases like:
var arr=[];arr[99]=1;//0 through 98 are undefined, but do NOT hold the undefined value
I want to remove those. And on the case I have some real undefined values, these should not be removed.
My poor attempt is this one:
var out=[];
for (var i=0,len=arr.length; i < len - 1;) {
var x = false;
var y = false;
for (var j = i, jo; j < len - 1; j++) {
if (j in arr) {
x = true;
jo = arr[j];
i = j + 1;
break;
}
}
if (x == false) {
break;
}
for (var u = i, yo; u < len - 1; u++) {
if (u in arr) {
y = true;
yo = arr[u];
i = u + 1;
break;
}
}
if (y == false) {
out.push(jo);
break;
}
if (jo !== yo) {
out.push(jo);
}
}
out.push(arr[len - 1]);
I am really lost, any help is appreciated
A modern one-liner using .filter()
arr.filter((e, i, a) => e !== a[i - 1]);
I'm very surprised by the complexity of other answers here, even those that use .filter()
Even using old-school ES5 syntax with no arrow functions:
arr.filter(function (e, i, a) { return e !== a[i - 1] });
Example:
let a = [0, 1, 1, 2, 2, 3, 4, 5, 5, 6, 7, 7, 8, 9, 9, 9];
let b = arr.filter((e, i, a) => e !== a[i - 1]);
console.log(b); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
If you need to mutate the array in place then just use:
arr = arr.filter((e, i, a) => e !== a[i - 1]);
Personally I would recommend against using such complex solutions as the ones in other answers here.
For a start, I'm not entirely certain your original code is kosher. It appears to me that it may not work well when the original list is empty, since you try to push the last element no matter what. It may be better written as:
var out = [];
var len = arr.length - 1;
if (len >= 0) {
for (var i = 0;i < len; i++) {
if (arr[i] !== arr[i+1]) {
out.push (arr[i]);
}
}
out.push (arr[len]);
}
As to your actual question, I'll answer this as an algorithm since I don't know a lot of JavaScript, but it seems to me you can just remember the last transferred number, something like:
# Set up output array.
out = []
# Set up flag indicating first entry, and value of last added entry.
first = true
last = 0
for i = 0 to arr.length-1:
# Totally ignore undefined entries (however you define that).
if arr[i] is defined:
if first:
# For first defined entry in list, add and store it, flag non-first.
out.push (arr[i])
last = arr[i]
first = false
else:
# Otherwise only store if different to last (and save as well).
if arr[i] != last:
out.push (arr[i])
last = arr[i]
This is a one-liner:
uniquify( myArray.filter(function(x){return true}) )
If you don't already have uniquify written (the function you wrote to remove duplicates), you could also use this two-liner:
var newArray = [];
myArray.forEach(function(x) {
if (newArray.length==0 || newArray.slice(-1)[0]!==x)
newArray.push(x)
})
Elaboration:
var a=[];
a[0]=1; a[1]=undefined; a[2]=undefined;
a[10]=2; a[11]=2;
According to OP, array has "five elements" even though a.length==12. Even though a[4]===undefined, it is not an element of the array by his definition, and should not be included.
a.filter(function(x){return true}) will turn the above array into [1, undefined, undefined, 2, 2].
edit: This was originally written with .reduce() rather than .forEach(), but the .forEach() version is much less likely to introduce garbage-collector and pass-by-value issues on inefficient implements of javascript.
For those concerned about compatibility with the 6-year-old MIE8 browser, which does not support the last two editions of the ECMAScript standard (and isn't even fully compliant with the one before that), you can include the code at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach However if one is that concerned about browser compatibility, one ought to program via a cross-compiler like GWT. If you use jQuery, you can also rewrite the above with only a few extra characters, like $.forEach(array, ...).
Perhaps something like this:
var out = [],
prev;
for(var i = 0; i < arr.length; i++) {
if (!(i in arr))
continue;
if (arr[i] !== prev || out.length === 0) {
out.push(arr[i]);
prev = arr[i];
}
}
The out.length check is to allow for the first defined array element having a value of undefined when prev also starts out initially as undefined.
Note that unlike your original algorithm, if arr is empty this will not push an undefined value into your out array.
Or if you have a new enough browser, you could use the Array.forEach() method, which iterates only over array elements that have been assigned a value.
An explicit way would be to pack the array (remove the undefined) values and use your existing algorithm for the duplicates on that..
function pack(_array){
var temp = [],
undefined;
for (i=0, len = _array.length; i< len; i++){
if (_array[i] !== undefined){
temp.push(_array[i]);
}
}
return temp;
}
I think this is what you want. It's a pretty simple algorithm.
var out = [], previous;
for(var i = 0; i < arr.length; i++) {
var current = arr[i];
if(!(i in arr)) continue;
if(current !== previous) out.push(current);
previous = arr[i];
}
This will run in O(N) time.
A very simple function, the input array must be sorted:
function removeDupes(arr) {
var i = arr.length - 1;
var o;
var undefined = void 0;
while (i > 0) {
o = arr[i];
// Remove elided or missing members, but not those with a
// value of undefined
if (o == arr[--i] || !(i in arr)) {
arr.splice(i, 1);
}
}
return arr;
}
It can probably be more concise, but might become obfuscated. Incidentally, the input array is modified so it doesn't need to return anything but it's probably more convenient if it does.
Here's a forward looping version:
function removeDupes2(arr) {
var noDupes = [],
o;
for (var i=0, j=0, iLen=arr.length; i<iLen; i++) {
o = arr[i];
if (o != noDupes[j] && i in arr) {
noDupes.push(o);
j = noDupes.length - 1;
}
}
return noDupes;
}
PS
Should work on any browser that supports javascript, without any additional libraries or patches.
This solution removes duplicates elements in-place. not recommended for functional programming
const arr =[0,0,1,1,2,2,2,3,4,5,5,6,7,7,8,9,9,9];
const removeDuplicates = (nums) => {
nums.forEach((element, idx) => {
nums.splice(idx, nums.lastIndexOf(element) - idx)
})
}
removeDuplicates(arr)
console.log(arr);
//sort the array
B.sort(function(a,b){ return a - b});
//removing duplicate characters
for(var i=0;i < B.length; i ++){
if(B[i]==B[i + 1])
B.splice(i,1)
}
if element in next index and current position is same remove the element at
current position
splice(targetPosition,noOfElementsToBeRemoved)
I believe what you are trying to achieve is not quite possible, but I could be wrong.
It's like one of those classic CS problems like the one where a barber in a village only shaves the one who don't shave themselves.
If you set the value of an array's index item as undefined, it's not really undefined.
Isn't that the case? A value can only be undefined when it hasn't been initialized.
What you should be checking for is whether a value is null or undefined. If null or duplicate skip the value, else retain it.
If null values and duplicates are what you are trying to skip then below function will do the trick.
function removeDuplicateAndNull(array){
if(array.length==0)
return [];
var processed = [], previous=array[0];
processed.push(array[0]);
for(var i = 1; i < array.length; i++) {
var value = array[i];
if( typeof value !== 'undefined' && value ==null)
continue;
if(value !== previous || typeof value === 'undefined')
processed.push(value);
previous = array[i];
}
return processed;
}
Test cases:
array=[,5,5,6,null,7,7] output =[ ,5,6,7]
array=[ 5,5,,6,null,,7,7] output=[5,,6,,7]
array=[7,7,,] output=[7,]
But even with this function there's a caveat. IF you check third test, the output is [7,]
instead of [7,,] !
If you check the length of the input and output arrays, array.length =3 and output.length=2.
The caveat is not with the function but with JavaScript itself.
This code is written in javascript. Its very simple.
Code:
function remove_duplicates(arr) {
newArr = [];
if (arr.length - 1 >= 0) {
for (i = 0; i < arr.length - 1; i++) {
// if current element is not equal to next
// element then store that current element
if (arr[i] !== arr[i + 1]) {
newArr.push(arr[i]);
}
}
newArr.push(arr[arr.length - 1]);
}
return newArr
}
arr=[0,1,1,2,2,3,4,5,5,6,7,7,8,9,9,9];
console.log(remove_duplicates(arr));
Here is the simple JavaScript solution without using any extra space.
function removeDuplicates(A) {
let i = 0;
let j = i + 1;
while (i < A.length && j < A.length) {
if (A[i] === A[j]) {
A.splice(i, 1);
j=i+1;
} else {
i++;
j++;
}
}
return A;
}
console.log('result', removeDuplicates([0,1,1,2,2,2,2,3,4,5,6,6,7]))
You can try the simple way
function hello(a: [], b: []) {
return [...a, ...b];
}
let arr = removeDuplicates(hello([1, 3, 7], [1, 5, 10]));
arr = removeDuplicates(arr);
function removeDuplicates(array) {
return array.filter((a, b) => array.indexOf(a) === b);
}
let mainarr = arr.sort((a, b) => parseInt(a) - parseInt(b));
console.log(mainarr); //1,3,5,7,10
One liner code
[1,3,7,1,5,10].filter((a, b) => [1,3,7,1,5,10].indexOf(a) === b).sort((a, b) => parseInt(a) - parseInt(b))
Here is simple solution to remove duplicates from sorted array.
Time Complexity O(n)
function removeDuplicate(arr) {
let i=0;
let newArr= [];
while(i < arr.length) {
if(arr[i] < arr[i+1]) {
newArr.push(arr[i])
} else if (i === (arr.length-1)) {
newArr.push(arr[i])
}
i++;
}
return newArr;
}
var arr = [1,2,3,4,4,5,5,5,6,7,7]
console.log(removeDuplicate(arr))
Let's suppose that you have a sorted array and you can't use additional array to find and delete duplicates:
In Python
def findDup(arr, index=1, _index=0):
if index >= len(arr):
return
if arr[index] != arr[_index]:
findDup(arr, index+1, _index+1)
if arr[index] == arr[_index]:
arr = deletedup(arr, index)
findDup(arr, index, _index) #Has to remain same here, because length has changed now
def deletedup(arr, del_index):
del arr[del_index]
return arr
arr = [1, 2, 3, 4, 4, 4, 5, 6, 7, 7, 7, 7, 7]
findDup(arr)
print arr

Categories

Resources