The function below will log the value of newData but returns undefined when called. Does anyone know why this might be? Also, any feedback on the function itself would be greatly appreciated!
export const filterByDateTimeRange = (data=[{}], timeKey=[], startTime=moment(), stopTime=moment()) => {
let newData = [];
let i = 0;
for(const item of data) {
let time;
let index = 0
timeKey.map(key => {
time ? time = time[key] : time = item[key];
index++
if(index === timeKey.length) {
if(moment(time).isBetween(startTime, stopTime, undefined, '[)')) {
newData.push(item)
};
i++;
if(i === data.length) {
console.log(newData);
return (newData);
}
}
})
}
}
The map function is usually used to transform a collection and store the results, for example:
var squares = [2, 3, 4].map(x => { return x * x });
// result is squares = [4, 9, 16]
The forEach function is more appropriate to use here since you just want to loop over the array and don't care about storing a transformation.
Then when the outer loop finishes your function can return newData
export const filterByDateTimeRange = (data=[{}], timeKey=[], startTime=moment(), stopTime=moment()) => {
let newData = [];
let i = 0;
for(const item of data) {
let time;
let index = 0
timeKey.forEach(key => { //changed to a forEach loop
time ? time = time[key] : time = item[key];
index++
if(index === timeKey.length) {
if(moment(time).isBetween(startTime, stopTime, undefined, '[)')) {
newData.push(item)
};
i++;
if(i === data.length) {
console.log(newData);
}
}
});
}
return newData; //add the return after your loop finishes
}
This return inside a map function. Not return of filterByDateTimeRange(). If you want to return newData. Replace map function by for loop.
Map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Related
I have such function and global variable (as array):
const arraysList = []
export const changeColorCategories = (array, draggedColumnId) => {
const isColor = arraysList.length ? arraysList[0][0]?.color : [];
if (typeof isColor === 'string') {
firstLevelColor = isColor;
}
return array.map((item, index, categories) => {
item.color = draggedColumnId !== 3 ? '#010172' : '#000000';
arraysList.push(categories);
if (firstLevelColor && !draggedColumnId) {
item.color = firstLevelColor;
}
if (item?.children?.length) {
changeColorCategories(item.children);
}
return item;
})
}
Every call of this function push some data to array. In this function I use recursion. So how i can clear this array only when this function will end it's work.
You can call the recursion function inside another function this way you can run anything you want when the function ends
const arraysList = []
export const changeColorCategories = (array, draggedColumnId) => {
const isColor = arraysList.length ? arraysList[0][0]?.color : [];
if (typeof isColor === 'string') {
firstLevelColor = isColor;
}
return array.map((item, index, categories) => {
item.color = draggedColumnId !== 3 ? '#010172' : '#000000';
arraysList.push(categories);
if (firstLevelColor && !draggedColumnId) {
item.color = firstLevelColor;
}
if (item?.children?.length) {
changeColorCategories(item.children);
}
return item;
})
}
function runRucFunc(){
const result = changeColorCategories();
//Your other code goes here
return result;
}
You can just put your recursion part inside a sub function.
Below I've called the inner function inner, I've also moved the arrayList into the function, due to closures you wound't even need to clear the arrayList, it would be cleared automatically as it goes out of scope.
eg.
export const changeColorCategories = (array, draggedColumnId) => {
const arraysList = []
function inner(array, draggedColumnId) {
const isColor = arraysList.length ? arraysList[0][0]?.color : [];
if (typeof isColor === 'string') {
firstLevelColor = isColor;
}
return array.map((item, index, categories) => {
item.color = draggedColumnId !== 3 ? '#010172' : '#000000';
arraysList.push(categories);
if (firstLevelColor && !draggedColumnId) {
item.color = firstLevelColor;
}
if (item?.children?.length) {
inner(item.children); //we call inner here instead.
}
return item;
})
}
// now call our inner
// you could do something even before your recursion.
const result = inner(array, draggedColumnId);
// here we can put what we want after recursion.
return result;
}
You could wrap the recursive call in another function like so:
const arr = []
const recursive = (counter = 0) => {
if(counter === 5)
return arr.map((v) => String.fromCodePoint(65 + v))
arr.push(counter)
return recursive(++counter)
}
const go = () => {
console.log(recursive()) // [A,B,C,D,E]
console.log(arr) // [0,1,2,3,4]
arr.length = 0 // clear the array
console.log(arr) // []
}
go()
Alternatively, if the global array does not actually need to be global, and is merely a container for working information of the recursive algorithm, then you could make it a parameter of the recursive function, which will then fall out of scope (and be garbage collected) when the recursion ends.
const recursive = (counter = 0, arr = []) => {
if(counter === 5)
return arr.map((v) => String.fromCodePoint(65 + v))
arr.push(counter)
return recursive(++counter, arr)
}
console.log(recursive()) // [A,B,C,D,E]
console.log(arr) // Error! Not in scope!
go()
Or, you could make the recursive function more intelligent and able to detect when it is processing the final recursion: how this is done will depend on the precise logic of the recursive function.
I am trying to remove duplicate JSON Objects from the array in ServiceNow.
Tried below code but it does not remove the duplicate. I want to compare both name & city.
var arr1 = '[{"name":"Pune","city":"India"},{"name":"Pune","city":"India"}]';
var splitlen = JSON.parse(arr1);
alert(splitlen.length);
var uniqueArray = [];
var uniqueJson = {};
for(i=0;i<splitlen.length;i++)
{
if(uniqueArray.indexOf(splitlen[i].name)==-1)
{
uniqueArray.push(splitlen[i]);
}
}
alert(JSON.stringify(uniqueArray));
Expected output :
[{"name":"Pune","city":"India"}]
uniqueArray.indexOf doesn't work because you're comparing objects against strings (splitlen[i].name). Try to use .find() instead:
var arr1 = '[{"name":"Pune","city":"India"},{"name":"Pune","city":"India"}]';
var splitlen = JSON.parse(arr1);
var uniqueArray = [];
var uniqueJson = {};
for(i=0;i<splitlen.length;i++)
{
if(!uniqueArray.find(x => x.name === splitlen[i].name))
{
uniqueArray.push(splitlen[i]);
}
}
console.log(uniqueArray);
or
var arr1 = '[{"name":"Pune","city":"India"},{"name":"Pune","city":"India"}]';
var splitlen = JSON.parse(arr1);
function compare(x){
return x.name === splitlen[i].name;
}
var uniqueArray = [];
var uniqueJson = {};
for(i=0;i<splitlen.length;i++)
{
if(!uniqueArray.find(compare))
{
uniqueArray.push(splitlen[i]);
}
}
console.log(uniqueArray);
you can try this. Also one more thing your array declaration is not right, remove single quotes from array.
var arr1 = [{"name":"Pune","city":"India"},{"name":"Pune","city":"India"}];
function getUniqueListByKey(arr, key) {
return [...new Map(arr.map(item => [item[key], item])).values()]
}
var arr2 = getUniqueListByKey(arr1, "name")
console.log(arr2);
Please try the following example
const arr1 = '[{"name":"Pune","city":"India"},{"name":"Pune","city":"India"}]';
const splitlen = JSON.parse(arr1);
const output = splitlen.reduce((previousValue, currentValue) => {
const { name, city } = currentValue;
const index = previousValue.findIndex(
(entry) => entry.name === name && entry.city === city
);
if (index === -1) {
return [...previousValue, currentValue];
}
return previousValue;
}, []);
console.log(output);
See
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
Put the records in a hashset. If there is collision in the hashset, there is duplicate. This approach is O(n) while comparing all pairs is $O(n^2)$.
I'm trying to get an answer, here's my idea:
Create a function to compare two objects then create a function to get the unique value
function isEquals(obj1, obj2) {
const aProps = Object.getOwnPropertyNames(obj1);
const bProps = Object.getOwnPropertyNames(obj2);
if (aProps.length !== bProps.length) {
return false;
}
for (let j = 0; j < aProps.length; j++) {
const propName = aProps[j];
if (JSON.stringify(obj1[propName]) !== JSON.stringify(obj2[propName])) {
return false;
}
} return true;
}
function getUnique(arr) {
var uniqueArray = [];
for (var item of arr) {
const uniqueItems = arr.filter(i => isEquals(item, i));
if (uniqueItems.length !== 0) {
uniqueArray.push(Object.assign({}, uniqueItems.shift()));
}
arr = arr.filter(i => !isEquals(item, i));
}
return uniqueArray;
}
Hope it helps!
I'm trying to create an algorithm to find duplicate values in a list and return their respective indexes, but the script only returns the correct value, when I have 2 equal elements:
array = [1,2,0,5,0]
result -> (2) [2,4]
Like the example below:
array = [0,0,2,7,0];
result -> (6) [0, 1, 0, 1, 0, 4]
The expected result would be [0,1,4]
Current code:
const numbers = [1,2,0,5,0];
const checkATie = avgList => {
let averages, tie, n_loop, currentAverage;
averages = [... avgList];
tie = [];
n_loop = 0;
for(let n = 0; n <= averages.length; n++) {
currentAverage = parseInt(averages.shift());
n_loop++
for(let avg of averages) {
if(avg === currentAverage) {
tie.push(numbers.indexOf(avg),numbers.indexOf(avg,n_loop))
};
};
};
return tie;
}
console.log(checkATie(numbers));
if possible I would like to know some way to make this code more concise and simple
Use a Set
return [...new Set(tie)]
const numbers1 = [1,2,0,5,0];
const numbers2 = [0,0,2,7,0];
const checkATie = avgList => {
let averages, tie, n_loop, currentAverage;
averages = [... avgList];
tie = [];
n_loop = 0;
for(let n = 0; n <= averages.length; n++) {
currentAverage = parseInt(averages.shift());
n_loop++
for(let avg of averages) {
if(avg === currentAverage) {
tie.push(avgList.indexOf(avg),avgList.indexOf(avg,n_loop))
};
};
};
return [...new Set(tie)]
}
console.log(checkATie(numbers1));
console.log(checkATie(numbers2));
I hope this help you.you can use foreach function to check each item of array
var array = [0,0,2,7,0];
var result = [] ;
array.forEach((item , index)=>{
if(array.findIndex((el , i )=> item === el && index !== i ) > -1 ){
result.push(index)
}
})
console.log(result);
//duplicate entries as an object
checkDuplicateEntries = (array) => {
const duplicates = {};
for (let i = 0; i < array.length; i++) {
if (duplicates.hasOwnProperty(array[i])) {
duplicates[array[i]].push(i);
} else if (array.lastIndexOf(array[i]) !== i) {
duplicates[array[i]] = [i];
}
}
console.log(duplicates);
}
checkDuplicateEntries([1,2,0,5,0]);
// hope this will help
Create a lookup object with value and their indexes and then filter all the values which occurred more than once and then merge all indexes and generate a new array.
const array = [1, 2, 0, 5, 0, 1, 0, 2],
result = Object.values(array.reduce((r, v, i) => {
r[v] = r[v] || [];
r[v].push(i);
return r;
}, {}))
.filter((indexes) => indexes.length > 1)
.flatMap(x => x);
console.log(result);
If I call the filter function, I get this array returned [ 1, , 3, , 5 ]. From where come the additional commas? I don't understand this effect. Can somebody explain it to me?
The array should be that: [ 1, 3, 5 ].
class List {
constructor(values = []) {
this._list = values;
}
filter(func) {
let newList = new Array();
let indexList = 0;
let indexNewList = 0;
while (this._list[indexList] != undefined) {
if (func(this._list[indexList]) === true) {
newList[indexNewList] = this._list[indexList];
indexNewList++;
}
indexList++;
}
this._list = newList;
return this;
}
get values() { return this._list }
}
var isOdd = function (x) {
return x % 2 === 1;
};
var list = new List([1, 2, 3, 4, 5]);
console.log(list.filter(isOdd).values);
If an item in the list matches the filter, you're inserting it into the new list at the index of the item in the original list. You want to simply be appending the item to the new list.
Use another variable to keep track of what index the element should be inserted into the new list at:
let newList = new Array();
let indexList = 0;
let newIndex = 0;
while (this._list[indexList] != undefined) {
if (func(this._list[indexList]) === true) {
newList[newIndex] = this._list[indexList];
newIndex++;
}
indexList++;
}
The newIndex variable will only be incremented when an item has been inserted into newList, instead of being incremented with every iteration of the loop.
The problem is the increment of the variable index, that increment is creating empty/undefined elements.
For example:
Array = [1];
index = 1
callback returns false
The index is incremented by 1 -> index =2`
Next iteration callback returns true
A new element is added to Array at position 2 ->
Array = [1, undefined, 3].
Use a separated index for the newArray.
class List {
constructor(values = []) {
this._list = values;
}
filter(func) {
let newList = new Array();
let index = 0;
let newListIndex = 0;
while (this._list[index] != undefined) {
if (func(this._list[index]) === true) {
newList[newListIndex++] = (this._list[index]);
}
index++;
}
this._list = newList;
return this;
}
get values() {
return this._list
}
}
var isOdd = function(x) {
return x % 2 === 1;
};
var list = new List([1, 2, 3, 4, 5]);
console.log(list.filter(isOdd));
I would suggest sticking with a functional-programming style definition of array#filter since that is the paradigm it originates from.
This is the fully immutable version of List#filter where you get a new instance of List back and the underlying array never goes through any form of mutation.
class List {
constructor(values = []) {
this._list = values;
}
filter(func) {
var reduce = function(values, accum) {
if(values.length === 0) return accum;
if(func(values[0])) return reduce(values.slice(1), accum.concat(values[0]));
else return reduce(values.slice(1), accum)
}
return new List(reduce(this._list, []))
}
get values() {
return this._list
}
}
var isOdd = function(x) {
return x % 2 === 1;
};
var list = new List([1, 2, 3, 4, 5]);
console.log(list.filter(isOdd));
This is my function in foreach loop for creating object which has property and value as word and its count, but i want to convert it in map according to es6
function harmlessRamsonNote(noteText,magazineText)
{
var noteArr = noteText.split(' ');
var magazineArr = magazineText.split(' ');
var magazineObj = {};
magazineArr.forEach(word => {
if(!magazineObj[word])
{
magazineObj[word] = 0;
}
magazineObj[word]++;
});
console.log(magazineObj);
};
magazineArr.map((word, index, array) => {
!magazineObj[word] ? magazineObj[word] = 0 : magazineObj[word]++;
})
map will return an new item for each item. Instead you can use reduce.
const magazineObj = magazineArr.reduce((acc,word) => {
acc[word] = (acc[word] || -1) + 1;
}, {});