JS delete duplicated items from array without higher order functions - javascript

I know it's a stupid question, but I only learning programming 3 months now.
How would you solve this problem, if you can't use higher order functions and built-in methods, like filter or indexOf?
Create a function that takes a list of numbers and returns a new list where all the duplicate values are removed
I got this so far, but I think It's a dead end...
const array = [1, 2, 3, 3, 1];
const removeDuplicate = () => {
let shortArray = [];
let index = 0;
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length; j++) {
if (i != j) {
if (array[i] == array[j]) {
shortArray[index] += array[i]
console.log(array[i]);
}
}
}
}
return shortArray;
}
console.log(removeDuplicate());
return this:
1
3
3
1
[ NaN ]
thanks!

Use an object as a helper. If a value appears in the helper, it's not unique and can be ignored. If it's not in the helper it's unique, push it into the result array, and add it to the helper object.
const array = [1, 2, 3, 3, 1];
const removeDuplicate = (arr) => {
const helperMap = {};
const result = [];
for (let i = 0; i < arr.length; i++) {
const item = arr[i];
if (!helperMap[item]) {
result[result.length] = item;
helperMap[item] = true;
}
}
return result;
};
console.log(removeDuplicate(array));

function unique(arr) {
var obj = {};
for (var i = 0; i < arr.length; i++) {
var value = arr[i];
obj[value] = true; // set as key
}
return Object.keys(obj); //return all keys
}

Use below function:
function RemoveDuplicate(array){
let shortArray = [];
let index = 0;
for (let i = 0; i < array.length; i++) {
let exist=false;
for(let j=0;j<shortArray.length;j++){
if(array[i]==shortArray[j]){
exist=true;
break;
}
}
if(!exist){
shortArray[shortArray.length]=array[i];
}
}
return shortArray;
}

Related

Why does my function keep coming back as undefined?

Here is the code I have. I am pretty new to javascript still so I don't see why adding the function stops the for statement from incrementing the integers.
const arr = [10,10,16,12]
function incrementByOne(arr) {
// arr is an array of integers(numbers), Increment all items in the array by
// return the array
for (const i = 0; i < arr.length; i++){
arr[i] += 1;
}
return arr
}
Any help would be greatly appreciated.
I ran your code under Node.js:
Code:
'use strict';
const arr = [10,10,16,12]
function incrementByOne(arr) {
for (const i = 0; i < arr.length; i++) {
arr[i] += 1;
}
return arr
}
console.log(incrementByOne(arr));
Output:
$ node incr.js
incr.js:6
for (const i = 0; i < arr.length; i++){
TypeError: Assignment to constant variable.
at incrementByOne (incr.js:6:37)
$
As you can see, it complains that you are trying to change the value of i which your code said was constant. Write let i = 0 for a non-constant value.
Code:
'use strict';
const arr = [10,10,16,12]
function incrementByOne(arr) {
for (let i = 0; i < arr.length; i++) {
arr[i] += 1;
}
return arr
}
console.log(incrementByOne(arr));
Output:
$ node incr.js
[ 11, 11, 17, 13 ]
$
You could use map also:
const incrementByOne = (arr) => arr.map((element) => element + 1);
You should use let i = 0 instead of const i= 0 to initilize the loop iteration counter i
const arr = [10,10,16,12]
function incrementByOne(arr) {
// arr is an array of integers(numbers), Increment all items in the array by
// return the array
for (let i = 0; i < arr.length; i++){
arr[i] += 1;
}
return arr
}
Then call incrementByOne function
incrementByOne(arr);
const arr = [10,10,16,12]
function incrementByOne(arr) {
// arr is an array of integers(numbers), Increment all items in the array by
// return the array
for (let i = 0; i < arr.length; i++){
arr[i] += 1;
}
return arr
}
let a = incrementByOne(arr)
console.log(a)

Join rest of the elements of an array with the first element

I'm trying the following logic and not sure which array function can help. I'm not able to use map or es6 but would like to see an answer.
I tried the following:
/* JS */ - This is not working and would like to see how to make it work.
var input = ['x','y','z'];
var powerSetResult = powerSet(input);
console.log(powerSetResult);
/*Ouput should be [''.'x','y','z','xy,'xz','yz','xyz']*/
function powerSet(arr) {
var data = [];
for(var i=0; i<arr.length; i++) {
arr[i] = arr[i] + arr[i+1];
data.push(arr[i]);
}
console.log(data);
return data;
}
/* ES 6 */ - Is there a better way to do this?
let input = ['x','y','z'];
let powerSetResult = powerSet(input);
console.log(powerSetResult);
/*Ouput should be [''.'x','y','z','xy,'xz','yz','xyz']*/
const powerSet(arr) {
let data = arr.map(([s1, s2, s3]) => [``,`${s1}`,`${s2}`,`${s3}`,`${s1}${s2}`,`${s1}${s3}`,`${s2}${s3}`,`${s1}${s2}${s3}`]);
console.log(data);
return data;
}
Certainly not the most efficient... but you could do this:
var input = ['x','y','z'];
var powerSetResult = powerSet(input);
console.log(powerSetResult);
function powerSet(arr, result) {
result = result || new Set();
const str = arr.join('');
for (let i = 0; i < arr.length; i++) {
for (let j = i; j <= arr.length; j++) {
result.add(str.slice(i, j));
}
powerSet([...arr.slice(0, i), ...arr.slice(i+1)], result)
}
return Array.from(result).sort((a, b) => {
return (a.length - b.length) || a.localeCompare(b);
});
}
/* Output should be [''.'x','y','z','xy,'xz','yz','xyz'] */
Caveat being it will only work for single letter elements, but is easily modifiable to accommodate more.

I am stuck at a JavaScript function that should count all unique items in an array

I wanted to create a function, that counts all unique Items in an array, but somehow I do not get any output.
This is my array!
let arr = ["hi", "hello", "hi"];
And this is the code I wrote so far:
function countUnique(arr) {
var counts = {};
for (var i = 0; i < arr.length; i++) {
counts[arr[i]] = 1 + (counts[arr[i]] || 0);
}
countUnique(arr);
}
console.log(countUnique(arr));
Your are counting values correctly, however then you are calling this method recursively countUnique(arr); and it results an error of call stack exceeded.
So just remove recursive call of method countUnique(arr); and return counted value counts:
function countUnique(arr) {
var counts = {};
for (var i = 0; i < arr.length; i++) {
counts[arr[i]] = 1 + (counts[arr[i]] || 0);
}
return counts;
}
let arr = ["hi", "hello", "hi"];
console.log(countUnique(arr));
JavaScript engine limits the maximal recursion depth. We can rely on it being 10000, some engines allow more.
You could take a Set and return the size.
const countUnique = array => new Set(array).size;
console.log(countUnique(["hi", "hello", "hi"]));
let arr = ["hi", "hello", "hi"];
function countUnique(arr) {
var counts = {};
for (var i = 0; i < arr.length; i++) {
if(arr[i] in counts) {
counts[arr[i]]++;
} else {
counts[arr[i]] = 1;
}
}
return Object.keys(counts).length;
}
console.log(countUnique(arr));

how to get distinct value from an array javascript

how can i get elements uniquely from an array if aa is twice time it should not count in a result if it is if a is three times it should count 1
var string = "aaabbccddde" // Expected result ade
var toArray = string.split("")
console.log(toArray)
var newArr = []
for(let i =0; i<toArray.length; i++) {
if(newArr.indexOf(toArray[i]) === -1) {
newArr.push(toArray[i])
}
}
console.log(newArr)
can't find the solution yet please guide thank
Maybe this function can help you:
function getUniques(str) {
const uniques = [];
const strs = str.split("");
for (let i = 0; i < strs.length; i++) {
const elm = strs[i];
for (let j = i; j < strs.length; j++) {
if(elm === uniques[uniques.length - 1]) break;
if (elm !== strs[j + 1]) {
uniques.push(elm);
break;
}
}
}
return uniques.join("");
}
Sample:
getUniques("aaaadaaabbbcccdeeeee22222222222232") // adabcde232

Javascript - count and remove from an object

I have an object with duplicate values and I want to count all those which have the same value and remove them.
var myArray = [{nr: 'bbc',}, {nr: 'bbc'}, {nr: 'bbc'}, {nr: ccc}];
from this array I want to create another array but remove the duplicated values and count them to be like this.
var myArray = [{nr: 'bbc',amount: 3}}, {nr: ccc,amount: 1}];
You could probably use a better format
var count = {};
for(var i = 0; i < myArray.length; ++i) {
if(typeof count[myArray[i].nr] == 'undefined') {
count[myArray[i].nr] = 0;
}
++count[myArray[i].nr];
}
and this wound yield somehing like:
count = {
bcc: 3,
ccc: 1
};
if you still need it with the structure you specified, then:
var newArray = [];
for(var k in count) {
newArray.push({
nr: k,
amount: count[k]
});
}
If you want the same structure, this will work for you
var newArray = [];
for (var i = 0; i < myArray.length; i++) {
var matched = false;
for (var j = 0; j < newArray.length; j++) {
if(myArray[i].nr === newArray[j].nr){
matched = true;
newArray[j].amount++;
break;
}
};
if(!matched)
newArray.push({nr:myArray[i].nr,amount:1});
};
console.log(newArray);

Categories