how to get distinct value from an array javascript - 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

Related

My loop isn't separating the array items that don't match on the other array, how can I do that?

I`m trying to .push() the array items on both arrays, that don't match on each other and then assign it to the new array empty that I've created.. but it just iterate and return 60 items repeated.
What am I doing wrong?
Note: I'm still studying that subject, so I'm sorry if what I am doing is dumb haha
const bobsFollowers = ['James', 'Caleb', 'Rita', 'Samantha'];
const tinasFollowers = ['Maurice', 'Caleb', 'Samantha'];
const mutualFollowers = [];
const notMutualFollowers = [];
for (let i = 0; i < bobsFollowers.length; i++) {
for (let j = 0; j < tinasFollowers.length; j++) {
if (bobsFollowers[i] === tinasFollowers[j]) {
mutualFollowers.push(tinasFollowers[j]);
}
for (let x = 0; x < tinasFollowers.length && bobsFollowers.length; x++) {
if (bobsFollowers[i] !== tinasFollowers[j] && tinasFollowers[j] !== bobsFollowers[i])
notMutualFollowers.push(bobsFollowers[i], tinasFollowers[j]);
}
}
}
console.log(mutualFollowers);
console.log(notMutualFollowers);
I thing that is.
Ojs: I like define a const like currentValue just to make more sense and make understanding easier.
for (let i = 0; i < bobsFollowers.length; i++) {
const currentName = bobsFollowers[i];
let isHaveSomeInArray = false;
for (let j = 0; j < tinasFollowers.length; j++) {
const currentComparation = tinasFollowers[j];
if (currentName === currentComparation) {
mutualFollowers.push(currentComparation);
isHaveSomeInArray = true;
}
}
if (!isHaveSomeInArray) {
notMutualFollowers.push(currentName);
}
}

Write function strLetterCount and return new string with the characters followed by the count

I need to write a function strLetterCount(word) that takes the string input, and returns a string followed by the count of occurrences.
Ex:
strLetterCount("coconut"); // "c2o2n1u1t1"
Here is what I have so far:
function strLetterCount (word){
let results = ""
for(let i = 0; i < word.length; i++) {
let charAt = word.charAt(i)
let count = 0
results += charAt
for (let j = 0; j < word.length ; j++)
{
if(word.charAt(j) === charAt)
{
count++
}
}
results += count
}
return results;
}
But the issue is that it returns c2o2c2o2n1u1t1 instead of c2o2n1u1t1. I'm not sure how to get rid of the duplicates
function strLetterCount (word){
let results = ""
for(let i = 0; i < word.length; i++) {
let charAt = word.charAt(i)
if (!results.includes(charAt)) // <----------------------
{
let count = 0
results += charAt
for (let j = 0; j < word.length ; j++)
{
if(word.charAt(j) === charAt)
{
count++
}
}
results += count
}
}
return results;
}
console.log(strLetterCount("coconut"));
Using String.prototype.split function, you can convert string into char array.
Based on that char array, using Array.prototype.reduce, you can get the duplicated char info.
With that duplicated info, can get the string linked using Array.prototype.map.
console.log(strLetterCount("coconut")); // "c2o2n1u1t1"
function strLetterCount(word) {
const wordArr = word.split('');
const duplicates = wordArr.reduce((acc, cur) => {
acc[cur] ? acc[cur] ++ : acc[cur] = 1;
return acc;
}, {});
return Object.entries(duplicates).map(([key, value]) => key + value).join('');
}
function strLetterCount(word) {
let results = {};
for (let i = 0; i < word.length; i++) {
let c = word.charAt(i)
results[c] = (results[c] || 0) + 1;
}
let r = '';
for (let c in results)
r += c + results[c];
return r;
}
console.log(strLetterCount("coconut")); // "c2o2n1u1t1"
Using the String split method, a Set, the Array map method and the Array join method you can do it in a single line of code
const strLetterCount = word => [...new Set(word.split(''))].map(l => `${l}${word.split(l).length - 1}`).join('');
console.log(strLetterCount('coconut'));

Reverse whole string while keeping the spaces at the same position

This is the code I have tried. If we input "We are farmers!" it should return "!s rem raferaeW" however the code I have returns "!s remr aferaeW"
function reverseStr(input){
var array1 = [];
var array2 = [];
var nWord;
for (var i = 0; i < input.length; i++) {
array1.push(input[i]);
}
var spaces = [];
for (var i = 0; i < array1.length; i++) {
if(array1[i] == " ") {
spaces.push(i);
}
}
console.log(array1);
console.log(spaces);
array2 = array1.slice().reverse();
var spaces2 = [];
for (var i = 0; i < array1.length; i++) {
if(array2[i] == " ") {
spaces2.push(i);
}
}
console.log(spaces2);
for (var i = spaces2.length - 1; i >=0; i--) {
array2.splice(spaces2[i], 1);
}
console.log(array2);
nWord = array2.join('');
console.log(nWord);
var array3 = [];
for (var i = 0; i < nWord.length; i++) {
array3.push(nWord[i]);
}
console.log(array3);
for (var i = spaces.length - 1; i >=0; i = i - 1) {
array3.splice(spaces[i], 0, " ");
}
console.log(array3);
var anWord = array3.join('');
return anWord;
}
var input = "We are farmers!";
reverseStr(input);
First I pushed each letter of the input into an array at "array1". Then I made an array for the indexes of the spaces of "array1" called "spaces."
Then "array2" is an array of "array1" reversed.
Then "spaces2" is an array of the indexes for "array2" and then I used a for loop to splice out the spaces in array2. Then "nWord" is "array2" combined to form a new word.
Then "array3" is an array for all of nWord's letters and I used a reverse for loop for try to input spaces into "array3" and using the indexes of the "spaces" array. Unfortunately, it is not returning "!s rem raferaeW" and IS returning "!s remr aferaeW".
I am trying to know how I can use the indexes of the "spaces" array to create spaces in "array3" at indexes 2 and 7.
You just need to make following change
//for (var i = spaces.length - 1; i >=0; i = i - 1) {
// array3.splice(spaces[i], 0, " ");
//}
for (var i = 0; i < spaces.length; i = i + 1) {
array3.splice(spaces[i], 0, " ");
}
You are reading spaces array in reverse but as the problem stated spaces should be at same place. Reading it from start to finish fixed the issue.
function reverseStr(input){
var array1 = [];
var array2 = [];
var nWord;
for (var i = 0; i < input.length; i++) {
array1.push(input[i]);
}
var spaces = [];
for (var i = 0; i < array1.length; i++) {
if(array1[i] == " ") {
spaces.push(i);
}
}
console.log(array1);
console.log(spaces);
array2 = array1.slice().reverse();
var spaces2 = [];
for (var i = 0; i < array1.length; i++) {
if(array2[i] == " ") {
spaces2.push(i);
}
}
console.log(spaces2);
for (var i = spaces2.length - 1; i >=0; i--) {
array2.splice(spaces2[i], 1);
}
console.log(array2);
nWord = array2.join('');
console.log(nWord);
var array3 = [];
for (var i = 0; i < nWord.length; i++) {
array3.push(nWord[i]);
}
console.log(array3);
//for (var i = spaces.length - 1; i >=0; i = i - 1) {
// array3.splice(spaces[i], 0, " ");
//}
for (var i = 0; i < spaces.length; i = i + 1) {
array3.splice(spaces[i], 0, " ");
}
console.log(array3);
var anWord = array3.join('');
return anWord;
}
var input = "We are farmers!";
reverseStr(input);
Here is my best crack at it.
const reverseStr = (input) => {
const revArr = input.replaceAll(' ', '').split('').reverse();
for (let i = 0; i < revArr.length; i++) {
if (input[i] === ' ') revArr.splice(i, 0, ' ');
}
return revArr.join('');
}
let words="Today Is A Good Day";
let splitWords=words.split(' ')
console.log(splitWords)
let r=[]
let ulta=splitWords.map((val,ind,arr)=>{
// console.log(val.split('').reverse().join(''))
return r.push(val.split('').reverse().join(''))
})
console.log(r.join(' '))

javascript find difference between arrays

i am working on angular 2 application, while i am trying to find the difference from 2 arrays(last seven days and missing date with in last seven days).
whenever the array initialized through the string its working fine like example code 1. but while getting data from database it doesn't work.
var array1 = ['20180605', '20180606', '20180607', '20180608', '20180609', '20180610', '20180611']
var array2 = ['20180606', '20180607', '20180608']
var ind
for (var i = 0; i < array2.length; i++) {
ind = array1.indexOf(array2[i])
if (ind > -1) {
array1.splice(ind, 1)
}
}
console.log('diff', array1)
but this method is not working
let datas = [
{'dateString': '20180607'},
{'dateString': '20180606'},
{'dateString': '20180608'}
]
let originalDataArray = []
for (let data of datas) {
originalDataArray.push(data.dateString)
}
let dataArray = []
function formatDate (subtractDate) {
let datestring
datestring = moment().subtract(6 - subtractDate, 'days').format('YYYY' + 'MM' + 'DD')
dataArray.push(datestring)
}
let lastSevenDaysArray = []
for (let i = 0; i < 7; i++) {
let date = formatDate(i)
}
var array1 = originalDataArray
var array2 = dataArray
var ind
for (var i = 0; i < array2.length; i++) {
ind = array1.indexOf(array2[i])
if (ind > -1) {
array1.splice(ind, 1)
}
}
console.log('diff', array1)
You have mixed up array1 and array2. The correct code will be as follows
for (var i = 0; i < array1.length; i++) {
ind = array2.indexOf(array1[i])
if (ind > -1) {
array2.splice(ind, 1)
}
}
console.log('diff', array1);
Also, I would suggest you to improve your code to following
let datas = [{'dateString': '20180607'},{'dateString': '20180606'},{'dateString': '20180608'}];
let originalDataArray = datas.map(({dateString}) => dateString);
let dataArray = []
for (let i = 0; i < 7; i++) {
dataArray.push(formatDate(i));
}
function formatDate (subtractDate) {
return moment().subtract(6 - subtractDate, 'days').format('YYYY' + 'MM' + 'DD')
}
dataArray = dataArray.filter(c => !originalDataArray.includes(c));
console.log('diff', dataArray)
If you have two arrays and one is shorter, there's a simpler solution to find the difference :
const array1 = ['20180605', '20180606', '20180607', '20180608', '20180609', '20180610', '20180611'];
const array2 = ['20180606', '20180607', '20180608'];
for (let el of array2) {
if (array1.includes(el)) {
array1.splice(array1.indexOf(el), 1);
}
}
console.log(array1);
This removes the elements from array2 in array1, leaving you only with element that are not in array2.

JS delete duplicated items from array without higher order functions

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;
}

Categories