Remove Strings, Keep Numbers In Array With JavaScript - javascript

Other articles talk about removing strings from an array based on a search term.
But I'm trying to indentify which elements are strings and which elements are numbers in an array, and then remove all strings to return a new array.
function filter_list(l) {
let newArray = [];
for (let i = 0; i < l.length; i ++) {
if (i !== "^[a-zA-Z0-9_.-]*$") {
newArray = newArray + i;
}
}
return newArray;
}
This is returning 0123.
Why is it not returning an array?
Why is if (i !== "^[a-zA-Z0-9_.-]*$") not working? How else can I check for when an element is a string (something in quotes) within the array?
https://www.codewars.com/kata/list-filtering/train/javascript
Thanks

You can is typeof keyword. and filter(). I have tested the code its passing all tests in codewars.
Using ES6 Arrow Function
function filter_list(l) {
return l.filter(x => typeof x === "number");
}
console.log(filter_list([1,2,'a','b']))
Without Arrow Function
function filter_list(l) {
return l.filter(function(x){
return typeof x === "number"
});
}
console.log(filter_list([1,2,'a','b']))
Using Simple Loops
function filter_list(l) {
let newArr = [];
for(let i = 0;i<l.length;i++){
if(typeof l[i] === "number") newArr.push(l[i]);
}
return newArr
}
console.log(filter_list([1,2,'a','b']))

Regex is not good way to parse such table. Try isNaN
console.log(
[1,2,3,4,5, 'a', 'b', 1, 3].filter(item => !isNaN(item) ? item : '')
)
If you want less hacky way try
function filter_list(l) {
// l is very bad name, because look similar to i
let newArray = [];
for (let i = 0; i < l.length; i ++) {
!isNaN(l[i]) ? newArray.push(l[i]) : ''
}
return newArray;
}
or even
for (let i = 0; i < l.length; i ++) {
!isNaN(l[i]) ? newArray[i] = l[i] : ''
}
Hovewer, this task can be done with regexes, but I cannot recommend this solution.
[1,2,3,4,5, 'a', 'b', 1, 3].join(' ').replace(/\D/gm, '').split('')

var numberArray: any[];
numberArray.filter(Number)
Using this you can filter only numbers in an array and then can performe what you want.

function filter_list(l) {
return l.filter(x => typeof x === "number");
}
console.log(filter_list([1,2,'a','b']))

I worked out a simple answer that will work as well using the same logic required to solve your problem. I used it on an example where you have an array of temperature values, and you want to remove all the values which are strings from the existing array, then populate the new empty array.You can use typeof operator to identify the type of value in the temperatures array at position i which is the index of that array element. If the type of that value is not a string then push the value of the temperatures array at the current index position to the new array.
const temperatures = [3, -2, -6, -1, 'error', 9, 13, 17, 15, 14, 9, 5];
const cleanTemperatures = [];
for (let i = 0; i < temperatures.length; i++) {
if (typeof temperatures[i] !== 'string') {
cleanTemperatures.push(temperatures[i]);
}
}

Related

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

Finding the sum of a nested array

I tried finding the sum of all numbers of a nested array, but I don't get it to work correctly. This is what I tried:
function arraySum(i) {
sum = 0;
for (a = 0; a < i.length; a++) {
if (typeof i[a] == 'number') {
sum += i[a];
} else if (i[a] instanceof Array) {
sum += arraySum(i[a]);
}
}
return sum;
}
When you try it out with the array [[1,2,3],4,5], it gets 6 as the answer, instead of 15.
Does somebody know where there is a mistake in it?
The problem with your code is that the sum and a variables are global, instead of local. Because of this you get an infinite loop (a from the first entry in the function is reset by the second entry, so the same elements are processed again).
Fix it by adding var to where sum and a are declared to make them local to the function:
function arraySum(i) {
var sum=0; // missing var added
for(var a=0;a<i.length;a++){ // missing var added
if(typeof i[a]=="number"){
sum+=i[a];
}else if(i[a] instanceof Array){
sum+=arraySum(i[a]);
}
}
return sum;
}
Demo: http://jsbin.com/eGaFOLA/2/edit
I know it's late, but they say "is never late" :)
const sumNestedArray = arr => arr.flat(Infinity).reduce((a,b)=> a+b, 0)
const sumNestedArray = arr => arr.flat(Infinity).reduce((a,b)=> a+b, 0)
console.log(sumNestedArray([1,[2], [2, 3, [4]]]))
sumNestedArray([1,[2], [2, 3, [4]]])
For 2018 this solution is clean and functional:
let arr = [[ 1, 2, 3], 4, 5]
arr.flat().reduce((d, i) => d + i)
Documentation for flat and reduce.
Recurse, for example
function arraySum(x) {
var sum = 0, i;
if (typeof x === 'number')
return x;
else if (x instanceof Array)
for (i = 0; i < x.length; ++i)
sum += arraySum(x[i]);
return sum;
}
arraySum([[1,2,3],4,5]); // 15
I didn't optimise this so that it's clear, you may want some more logic before recursion.
The reason yours isn't working is because you need to var both sum and a.
You're missing two var in there. You've implicitly declared sum and a at window scope:
function arraySum(i) {
**var** sum=0;
for(**var** a=0;a<i.length;a++){
if(typeof i[a]=="number"){
sum+=i[a];
}else if(i[a] instanceof Array){
sum+=arraySum(i[a]);
}
}
return sum;
}
First of all why you use 'i' as input to function? we using 'i' to denote running index..
Regarding your question,you want 'a' to be local in your loop so instead of "for(a=0;..." instead write "for(var a=0;"
<html>
<body>
<script>
function NestedArraySummation(arr)
{
var sum=0;
for(var i=0;i<arr.length;i++)
{
if(typeof arr[i]=="number")
sum=sum+arr[i];
else if(arr[i] instanceof Array)
sum=sum+NestedArraySummation(arr[i]);
}
return sum;
}
var MyArray=[1,[2,3],4,10,[1,2]];
var Sum=NestedArraySummation(MyArray);
document.write(Sum);
</script>
</body>
</html>
This can be done with lodash _.flattenDeep and _.sum:
const arr = [[1, 2, 3], 4, 5];
arraySum(arr);
function arraySum(arr) {
var arrFlattens = _.flattenDeep(arr);
// => [1, 2, 3, 4, 5]
console.log(_.sum(arrFlattens));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Here you go:
(My assumption is that you want to parse strings, e.g., '13', into numbers in order include them in the sum. If not, just change isNumber to typeof val === 'number'.
function arraySum(arr) {
let sum = 0;
while (arr.length) {
const val = arr.pop();
const isArray = typeof val === 'object' && val.length !== undefined;
const isNumber = !isArray && !isNaN(sum + parseFloat(val));
if (isArray && val.length) {
sum += arraySum(val);
}
else if (isNumber) {
sum += parseFloat(val);
}
}
return sum;
}
console.log(arraySum([])); //0
console.log(arraySum([1, 1, 1, [3, 4, [8]], [4]])); //22
console.log(arraySum([1, 1, [], {}, 'l', 1, [3, 4, [8]], [4]])); //22
This was posted long ago but it might help others. I did the following and it seems to be working just fine
function countArray (array) {
//iterate through the array
for(let i = 0;i < array.length; i++){
//check if element of array is an array, and if it is, run method flat() to the whole array.
if(Array.isArray(array[i])){
array = array.flat()
}
}
//return the sum of the elements of the array
return array.reduce((a,b) => a + b);
}
from __builtin__ import int
def nestedLists(mylist):
sum = 0
if checkIfAllInt(mylist):
result = addList(mylist)
return result
else:
for value in mylist:
sum = sum + nestedLists(value)
return sum
def addList(listdata):
if(type(listdata) is int):
return listdata
else:
return sum(listdata)
def checkIfAllInt(listdata):
check = True
if(type(listdata) is int):
return check
else:
for value in listdata:
if(not type(value) is int):
check = False
return check
return check
print nestedLists([1,[2,3,[4,5,[6,7]]]])

Count unique elements in array without sorting

In JavaScript the following will find the number of elements in the array. Assuming there to be a minimum of one element in the array
arr = ["jam", "beef", "cream", "jam"]
arr.sort();
var count = 1;
var results = "";
for (var i = 0; i < arr.length; i++)
{
if (arr[i] == arr[i+1])
{
count +=1;
}
else
{
results += arr[i] + " --> " + count + " times\n" ;
count=1;
}
}
Is it possible to do this without using sort() or without mutating the array in any way? I would imagine that the array would have to be re-created and then sort could be done on the newly created array, but I want to know what's the best way without sorting.
And yes, I'm an artist, not a programmer, your honour.
The fast way to do this is with a new Set() object.
Sets are awesome and we should use them more often. They are fast, and supported by Chrome, Firefox, Microsoft Edge, and node.js.
— What is faster Set or Object? by Andrei Kashcha
The items in a Set will always be unique, as it only keeps one copy of each value you put in. Here's a function that uses this property:
function countUnique(iterable) {
return new Set(iterable).size;
}
console.log(countUnique('banana')); //=> 3
console.log(countUnique([5,6,5,6])); //=> 2
console.log(countUnique([window, document, window])); //=> 2
This can be used to count the items in any iterable (including an Array, String, TypedArray, and arguments object).
A quick way to do this is to copy the unique elements into an Object.
var counts = {};
for (var i = 0; i < arr.length; i++) {
counts[arr[i]] = 1 + (counts[arr[i]] || 0);
}
When this loop is complete the counts object will have the count of each distinct element of the array.
Why not something like:
var arr = ["jam", "beef", "cream", "jam"]
var uniqs = arr.reduce((acc, val) => {
acc[val] = acc[val] === undefined ? 1 : acc[val] += 1;
return acc;
}, {});
console.log(uniqs)
Pure Javascript, runs in O(n). Doesn't consume much space either unless your number of unique values equals number of elements (all the elements are unique).
Same as this solution, but less code.
let counts = {};
arr.forEach(el => counts[el] = 1 + (counts[el] || 0))
This expression gives you all the unique elements in the array without mutating it:
arr.filter(function(v,i) { return i==arr.lastIndexOf(v); })
You can chain it with this expression to build your string of results without sorting:
.forEach(function(v) {
results+=v+" --> " + arr.filter(function(w){return w==v;}).length + " times\n";
});
In the first case the filter takes only includes the last of each specific element; in the second case the filter includes all the elements of that type, and .length gives the count.
This answer is for Beginners. Try this method you can solve this problem easily. You can find a full lesson for reduce, filter, map functions from This link.
const user = [1, 2, 2, 4, 8, 3, 3, 6, 5, 4, 8, 8];
const output = user.reduce(function (acc, curr) {
if (acc[curr]) {
acc[curr] = ++acc[curr];
} else {
acc[curr] = 1;
}
return acc;
}, {});
console.log(output);
function reomveDuplicates(array){
var newarray = array.filter( (value, key)=>{
return array.indexOf(value) == key
});
console.log("newarray", newarray);
}
reomveDuplicates([1,2,5,2,1,8]);
Using hash Map with the time complexity O(n)
function reomveDuplicates(array){
var obj ={};
let res=[];
for( arg of array){
obj[arg] = true;
}
console.log(Object.keys(obj));
for(key in obj){
res.push(Number(key)); // Only if you want in Number
}
console.log(res);
}
reomveDuplicates([1,2,5,2,1,8]);
In a modern, extensible and easy-to-read approach, here's one using iter-ops library:
import {pipe, distinct, count} from 'iter-ops';
const arr = ['jam', 'beef', 'cream', 'jam'];
const count = pipe(arr, distinct(), count()).first;
console.log(count); //=> 3
function check(arr) {
var count = 0;
for (var ele of arr) {
if (typeof arr[ele] !== typeof (arr[ele+1])) {
count++;
} else {
("I don't know");
}
}
return count;
}

How to get unique values in an array [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 1 year ago.
How can I get a list of unique values in an array? Do I always have to use a second array or is there something similar to java's hashmap in JavaScript?
I am going to be using JavaScript and jQuery only. No additional libraries can be used.
Here's a much cleaner solution for ES6 that I see isn't included here. It uses the Set and the spread operator: ...
var a = [1, 1, 2];
[... new Set(a)]
Which returns [1, 2]
Or for those looking for a one-liner (simple and functional) compatible with current browsers:
let a = ["1", "1", "2", "3", "3", "1"];
let unique = a.filter((item, i, ar) => ar.indexOf(item) === i);
console.log(unique);
Update 2021
I would recommend checking out Charles Clayton's answer, as of recent changes to JS there are even more concise ways to do this.
Update 18-04-2017
It appears as though 'Array.prototype.includes' now has widespread support in the latest versions of the mainline browsers (compatibility)
Update 29-07-2015:
There are plans in the works for browsers to support a standardized 'Array.prototype.includes' method, which although does not directly answer this question; is often related.
Usage:
["1", "1", "2", "3", "3", "1"].includes("2"); // true
Pollyfill (browser support, source from mozilla):
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
Object.defineProperty(Array.prototype, 'includes', {
value: function(searchElement, fromIndex) {
// 1. Let O be ? ToObject(this value).
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// 3. If len is 0, return false.
if (len === 0) {
return false;
}
// 4. Let n be ? ToInteger(fromIndex).
// (If fromIndex is undefined, this step produces the value 0.)
var n = fromIndex | 0;
// 5. If n ≥ 0, then
// a. Let k be n.
// 6. Else n < 0,
// a. Let k be len + n.
// b. If k < 0, let k be 0.
var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 7. Repeat, while k < len
while (k < len) {
// a. Let elementK be the result of ? Get(O, ! ToString(k)).
// b. If SameValueZero(searchElement, elementK) is true, return true.
// c. Increase k by 1.
// NOTE: === provides the correct "SameValueZero" comparison needed here.
if (o[k] === searchElement) {
return true;
}
k++;
}
// 8. Return false
return false;
}
});
}
Since I went on about it in the comments for #Rocket's answer, I may as well provide an example that uses no libraries. This requires two new prototype functions, contains and unique
Array.prototype.contains = function(v) {
for (var i = 0; i < this.length; i++) {
if (this[i] === v) return true;
}
return false;
};
Array.prototype.unique = function() {
var arr = [];
for (var i = 0; i < this.length; i++) {
if (!arr.contains(this[i])) {
arr.push(this[i]);
}
}
return arr;
}
var duplicates = [1, 3, 4, 2, 1, 2, 3, 8];
var uniques = duplicates.unique(); // result = [1,3,4,2,8]
console.log(uniques);
For more reliability, you can replace contains with MDN's indexOf shim and check if each element's indexOf is equal to -1: documentation
One Liner, Pure JavaScript
With ES6 syntax
list = list.filter((x, i, a) => a.indexOf(x) === i)
x --> item in array
i --> index of item
a --> array reference, (in this case "list")
With ES5 syntax
list = list.filter(function (x, i, a) {
return a.indexOf(x) === i;
});
Browser Compatibility: IE9+
Using EcmaScript 2016 you can simply do it like this.
var arr = ["a", "a", "b"];
var uniqueArray = Array.from(new Set(arr)); // Unique Array ['a', 'b'];
Sets are always unique, and using Array.from() you can convert a Set to an array. For reference have a look at the documentations.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
These days, you can use ES6's Set data type to convert your array to a unique Set. Then, if you need to use array methods, you can turn it back into an Array:
var arr = ["a", "a", "b"];
var uniqueSet = new Set(arr); // {"a", "b"}
var uniqueArr = Array.from(uniqueSet); // ["a", "b"]
//Then continue to use array methods:
uniqueArr.join(", "); // "a, b"
If you want to leave the original array intact,
you need a second array to contain the uniqe elements of the first-
Most browsers have Array.prototype.filter:
const unique = array1.filter((item, index, array) => array.indexOf(item) === index);
//if you need a 'shim':
Array.prototype.filter= Array.prototype.filter || function(fun, scope){
var T= this, A= [], i= 0, itm, L= T.length;
if(typeof fun== 'function'){
while(i<L){
if(i in T){
itm= T[i];
if(fun.call(scope, itm, i, T)) A[A.length]= itm;
}
++i;
}
}
return A;
}
Array.prototype.indexOf= Array.prototype.indexOf || function(what, i){
if(!i || typeof i!= 'number') i= 0;
var L= this.length;
while(i<L){
if(this[i]=== what) return i;
++i;
}
return -1;
}
Fast, compact, no nested loops, works with any object not just strings and numbers, takes a predicate, and only 5 lines of code!!
function findUnique(arr, predicate) {
var found = {};
arr.forEach(d => {
found[predicate(d)] = d;
});
return Object.keys(found).map(key => found[key]);
}
Example: To find unique items by type:
var things = [
{ name: 'charm', type: 'quark'},
{ name: 'strange', type: 'quark'},
{ name: 'proton', type: 'boson'},
];
var result = findUnique(things, d => d.type);
// [
// { name: 'charm', type: 'quark'},
// { name: 'proton', type: 'boson'}
// ]
If you want it to find the first unique item instead of the last add a found.hasOwnPropery() check in there.
Not native in Javascript, but plenty of libraries have this method.
Underscore.js's _.uniq(array) (link) works quite well (source).
If you don't need to worry so much about older browsers, this is exactly what Sets are designed for.
The Set object lets you store unique values of any type, whether
primitive values or object references.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
const set1 = new Set([1, 2, 3, 4, 5, 1]);
// returns Set(5) {1, 2, 3, 4, 5}
Using jQuery, here's an Array unique function I made:
Array.prototype.unique = function () {
var arr = this;
return $.grep(arr, function (v, i) {
return $.inArray(v, arr) === i;
});
}
console.log([1,2,3,1,2,3].unique()); // [1,2,3]
Short and sweet solution using second array;
var axes2=[1,4,5,2,3,1,2,3,4,5,1,3,4];
var distinct_axes2=[];
for(var i=0;i<axes2.length;i++)
{
var str=axes2[i];
if(distinct_axes2.indexOf(str)==-1)
{
distinct_axes2.push(str);
}
}
console.log("distinct_axes2 : "+distinct_axes2); // distinct_axes2 : 1,4,5,2,3
Majority of the solutions above have a high run time complexity.
Here is the solution that uses reduce and can do the job in O(n) time.
Array.prototype.unique = Array.prototype.unique || function() {
var arr = [];
this.reduce(function (hash, num) {
if(typeof hash[num] === 'undefined') {
hash[num] = 1;
arr.push(num);
}
return hash;
}, {});
return arr;
}
var myArr = [3,1,2,3,3,3];
console.log(myArr.unique()); //[3,1,2];
Note:
This solution is not dependent on reduce. The idea is to create an object map and push unique ones into the array.
You only need vanilla JS to find uniques with Array.some and Array.reduce. With ES2015 syntax it's only 62 characters.
a.reduce((c, v) => b.some(w => w === v) ? c : c.concat(v)), b)
Array.some and Array.reduce are supported in IE9+ and other browsers. Just change the fat arrow functions for regular functions to support in browsers that don't support ES2015 syntax.
var a = [1,2,3];
var b = [4,5,6];
// .reduce can return a subset or superset
var uniques = a.reduce(function(c, v){
// .some stops on the first time the function returns true
return (b.some(function(w){ return w === v; }) ?
// if there's a match, return the array "c"
c :
// if there's no match, then add to the end and return the entire array
c.concat(v)}),
// the second param in .reduce is the starting variable. This is will be "c" the first time it runs.
b);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Another thought of this question. Here is what I did to achieve this with fewer code.
var distinctMap = {};
var testArray = ['John', 'John', 'Jason', 'Jason'];
for (var i = 0; i < testArray.length; i++) {
var value = testArray[i];
distinctMap[value] = '';
};
var unique_values = Object.keys(distinctMap);
console.log(unique_values);
Array.prototype.unique = function () {
var dictionary = {};
var uniqueValues = [];
for (var i = 0; i < this.length; i++) {
if (dictionary[this[i]] == undefined){
dictionary[this[i]] = i;
uniqueValues.push(this[i]);
}
}
return uniqueValues;
}
I have tried this problem in pure JS.
I have followed following steps 1. Sort the given array, 2. loop through the sorted array, 3. Verify previous value and next value with current value
// JS
var inpArr = [1, 5, 5, 4, 3, 3, 2, 2, 2,2, 100, 100, -1];
//sort the given array
inpArr.sort(function(a, b){
return a-b;
});
var finalArr = [];
//loop through the inpArr
for(var i=0; i<inpArr.length; i++){
//check previous and next value
if(inpArr[i-1]!=inpArr[i] && inpArr[i] != inpArr[i+1]){
finalArr.push(inpArr[i]);
}
}
console.log(finalArr);
Demo
You can enter array with duplicates and below method will return array with unique elements.
function getUniqueArray(array){
var uniqueArray = [];
if (array.length > 0) {
uniqueArray[0] = array[0];
}
for(var i = 0; i < array.length; i++){
var isExist = false;
for(var j = 0; j < uniqueArray.length; j++){
if(array[i] == uniqueArray[j]){
isExist = true;
break;
}
else{
isExist = false;
}
}
if(isExist == false){
uniqueArray[uniqueArray.length] = array[i];
}
}
return uniqueArray;
}
Here is an approach with customizable equals function which can be used for primitives as well as for custom objects:
Array.prototype.pushUnique = function(element, equalsPredicate = (l, r) => l == r) {
let res = !this.find(item => equalsPredicate(item, element))
if(res){
this.push(element)
}
return res
}
usage:
//with custom equals for objects
myArrayWithObjects.pushUnique(myObject, (left, right) => left.id == right.id)
//with default equals for primitives
myArrayWithPrimitives.pushUnique(somePrimitive)
I was just thinking if we can use linear search to eliminate the duplicates:
JavaScript:
function getUniqueRadios() {
var x=document.getElementById("QnA");
var ansArray = new Array();
var prev;
for (var i=0;i<x.length;i++)
{
// Check for unique radio button group
if (x.elements[i].type == "radio")
{
// For the first element prev will be null, hence push it into array and set the prev var.
if (prev == null)
{
prev = x.elements[i].name;
ansArray.push(x.elements[i].name);
} else {
// We will only push the next radio element if its not identical to previous.
if (prev != x.elements[i].name)
{
prev = x.elements[i].name;
ansArray.push(x.elements[i].name);
}
}
}
}
alert(ansArray);
}
HTML:
<body>
<form name="QnA" action="" method='post' ">
<input type="radio" name="g1" value="ANSTYPE1"> good </input>
<input type="radio" name="g1" value="ANSTYPE2"> avg </input>
<input type="radio" name="g2" value="ANSTYPE3"> Type1 </input>
<input type="radio" name="g2" value="ANSTYPE2"> Type2 </input>
<input type="submit" value='SUBMIT' onClick="javascript:getUniqueRadios()"></input>
</form>
</body>

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