How to get other index from the current index - javascript

i'm a newbie on JavaScript, help me to fix the problem i got.
I have an array, i want to remove class list for other div which are not same with the current index. Please help
i tried to find the answer from other discussion, but i still don't get what i want.
Here's the code:
window.addEventListener("load", ()=> {
const sounds = document.querySelectorAll(".sound");
const pads = document.querySelectorAll(".pads div");
const visual = document.querySelector(".visual");
pads.forEach((pad, index) => {
pad.addEventListener("click", function() {
sounds[index].currentTime = 0;
sounds[index].play();
popUpNote();
const ind = index + 1;
//I Need to got the other index from the current index,
//like if current index is 2, then i want to get 0,1,3,4,5
//since i have 6 index inside
pad.classList.add("active-pad"+ind);
sounds[index].addEventListener("ended", function() {
const noteChild = document.querySelector(".visual div");
noteChild.remove();
pad.classList.remove("active-pad"+ind);
});
});
});
const popUpNote = () => {
const note = document.createElement("div");
visual.appendChild(note);
note.style.animation = 'beatOn 1.5s ease-in-out infinite both';
};
});
I want to got the other index from the current index, like if the current index is 2, then i want to get 0,1,3,4,5 since i have 6 index inside

Through this , might you get your solution ,
In this JS script , you will not get the current index .
var arr = [1 , 2 , 3 , 4 , 5 , 6];
arr.forEach(function(valuw , index){
console.log(valuw , index);
for(var i = 0 ; i < arr.length ; i++){
if( i != index){
console.log("index at " , index , "itereator ===>" , i+1);
}
}
});

Use Array.filter() to find the other indexes:
const idxs = [0,1,2,3,4,5,6,7,8,9,10]
const cur = 4
const res = idxs.filter(idx => idx !== cur)
console.log(res)

Related

Checking for "triplicates" strings in JavaScript array

trying to find the best way to check for triplicates values inside an array of strings.
I found many stackoverflow solutions for duplicates values which is not the case in here.
This is the farest i could get with solving this and I am not sure if it is the correct way:
const array = [
"peace",
"peace",
"Vrede",
"Patz",
"Salam",
"paz",
"Salam",
"Salam"
];
const findTriplicates = (param) => {
let counts = {};
for (let i = 0; i < param.length; i++) {
if (counts[param[i]]) {
counts[param[i]] += 1;
} else {
counts[param[i]] = 1;
}
}
for (let i in counts) {
if (counts[i] === 3) {
console.log(i + " exists " + counts[i] + " times.");
}
}
};
findTriplicates(array); // Salam exists 3 times.
please don't hesitate to fix my code or to post your solution.
thanks for your support in advance :)
Cheerz!
Your overall idea is good, using Hash Maps (js objects) is the best option for the task.
You can move your "=== 3" check to the first loop and have another object to save triplicates, it will be twice faster.
check this out
const findTriplicates = (param) => {
let values = [...new Set(param)];
let triples = [];
values.forEach(item=>{
let counter = 0;
param.forEach(s=>{
if(s===item) counter++;
})
if(3==counter) triples.push(item);
})
return triples;
};
There is no correct way to do things like this. You can always optimize or sacrifice performance for readability, but that is up to the developer.
I changed nothing about the functionality in findTriplicates, but the code is very different.
findTriplicates2 works a little different but is by no means superior
const array = [
"peace",
"peace",
"Vrede",
"Patz",
"Salam",
"paz",
"Salam",
"Salam"
];
const findTriplicates = (param) => {
let counts = param.reduce((acc, p) => {
acc[p] ? acc[p]++ : acc[p] = 1
return acc;
}, {})
Object.keys(counts).forEach((key) => counts[key] === 3 &&
console.log(`${key} exists 3 times.`)
);
};
findTriplicates(array); // Salam exists 3 times.
const findTriplicates2 = (param) => {
let triples = [...new Set(param)].reduce((acc, item) => {
let counter = param.reduce((acc2, s) => {
if (s === item) acc2++;
return acc2;
}, 0);
if (3 == counter) acc.push(item);
return acc;
}, [])
triples.forEach((triple) => console.log(`${triple} exists 3 times.`));
};
findTriplicates2(array); // Salam exists 3 times.
You create an object to keep count of how many times the string repeats and then iterate through each element in the array while updating the count in the object. Then you filter through that object for any values equal to 3.
const array = [
'peace',
'peace',
'Vrede',
'Patz',
'Salam',
'paz',
'Salam',
'Salam',
];
// Object to keep count of each word
const countObj = {};
// Iterate through the array to get the count for each word
array.forEach((element) => {
// Does word exist in the count object? if so -> add 1 to its count, else -> add word and count 1 to the object
countObj[element] ? (countObj[element] += 1) : (countObj[element] = 1);
});
// Filter out keys that appear exactly 3 times and print them them
const filteredArray = Object.keys(countObj).filter(
(key) => countObj[key] === 3
);
console.log(filteredArray); // Salam

Finding same array element in a different array and renaming it to be incremental

Finding same array element in another array and renaming it to be incremental. in the script below , i would like to increment the same element to +1 dynamically without manually putting in "motor" for it to be rename as "motor 1"
For an example , use case
//original array
["car","motor","bicycle","tricyle","motor"]
//result should be
["car","motor","bicycle","tricyle","motor 1"]
This is the script i tried
let _temparr = ["car","motor","bicycle","tricyle","motor"]
let _newarr = new Array();
let counter = 0;
for(let i = 0 ; i < _temparr.length;i++){
// Push _temparr element to _newarr
for(let a = 0; a < _newarr.length; a++){
// if _newarr consist of motor , increment counter +1 and push as "Motor 1"
if(_newarr[i] === "motor"){
counter++
_newarr.push(_temparr[i] + counter)
}
}
_newarr.push(_temparr[i])
The logic i came out with is, i will loop _temparray and push it to a new arrau which is :_newarr , within the first loop of _newarr if it finds the same element in _temparray. counter will increment . but im nnot sure what is the best practice to do this. i found some topics on using const found = arr1.some(r=> arr2.includes(r)) but this will remove if it has the same element
You can keep a counter for every word/element and use .map to create the new array, updating each element as needed:
const counter = new Map();
console.log(
["car","motor","bicycle","tricyle","motor"].map(
element => {
if (!counter.has(element)) {
counter.set(element, 1);
return element;
}
const count = counter.get(element);
counter.set(element, count+1);
return element + " " + count;
}
)
);
Maybe you could consider using a Map:
const originalArray = ["car", "motor", "bicycle", "tricyle", "motor"];
const newArray = [];
const counter = new Map();
originalArray.forEach(item => {
if (counter.has(item)) {
newArray.push(`${item} ${counter.get(item)}`);
counter.set(item, counter.get(item) + 1);
} else {
newArray.push(item);
counter.set(item, 1);
}
});
console.log(newArray);

decrementing after array mapping not working

I have a function "Next "that maps an array like in the example below and after incrementing the element I am doing something, but I also have another function "Prev" it pretty much does a similar mapping but in that function, I am decrementing the element. The Next function works fine but the Prev function doesn't, can someone please help me with this?
I am mapping an array of object
[
{
"id":"v82b3a65",
"name":"Name"
},
{
"id":"u0b26551",
"name":"Name2"
}
]
my functions :
const Next = () => {
array.items.map((item, key, element) => {
var next = element[key ++];
setId(next.id);
});
};
const Prev = () => {
array.items.map((item, key, element) => {
var prev = element[key --];
setId(prev.id);
});
};
render(
<View>
<Button title={'Prev'} onPress={Prev}/>
<Button title={'Next'} onPress={Next}/>
</View>
)
I am using those functions in onPress of buttons
The result I need: on Next button press I want it to set setID = next objects id and on Prev button press I want to set setID = previous object id
You should check index value if it is larger than 0 in Prev function. Also check if it is smaller than array length - 1 in Next function.
const Next = () => {
var newArray = myArray.map(function (value, index, elements) {
if (index < myArray.length - 1) {
var next = elements[index + 1];
// do something
}
});
};
const Prev = () => {
var newArray = myArray.map(function (value, index, elements) {
if (index > 0) {
var next = elements[index - 1];
// do something
}
});
};

Find the first unique value in an array or string

How can I get one unique value in an array or string? Only the first value. Pure JS only.
My example:
function searchValue () {
let inputText = [1,1,4,2,2,2,3,1];
let foundedValue;
for (let i = 0; i < inputText.length; i++) {
if (i === inputText.indexOf(inputText[i]) && i === inputText.lastIndexOf(inputText[i])) {
foundedValue = inputText[i];
break;
} else {
foundedValue = "not founded.";
}
}
return foundedValue;
}
console.log("Search value: "+ searchValue())
Answer is 4.
But, I need a short solution. Using the find() and filter() functions.
You can find the first unique item in your array using find() and comparing indexOf() to lastIndexOf() to determine whether or not there is more than one instance of an item in the array. If you need to find unique characters in a string, then you can first split it into an array and then use the same approach.
const arr = [1, 1, 4, 2, 2, 2, 3, 1];
const result = arr.find((x) => arr.indexOf(x) === arr.lastIndexOf(x));
console.log(result);
// 4
const text = 'aadbbbca';
const textarr = text.split('');
const textresult = textarr.find((x) => textarr.indexOf(x) === textarr.lastIndexOf(x));
console.log(textresult);
// d
You can try this.
const arr = [1, 1, 4, 2, 2, 2, 3, 1];
let r = {};
arr.map(a => r[a] = (r[a] || 0) +1)
var res = arr.find(a => r[a] === 1 )
console.log(res)
You can use js Set() object.
At first you could create a Set of duplicated elements.
const inputText = [1,1,4,2,2,2,3,1];
const duplicatesSet= inputText.reduce((dupSet, el) =>
inputText.filter(arrEl => arrEl === el).length > 1 ?
dupSet.add(el) : dupSet
, new Set());
Second you could use array.find. It returns first duplicated element.
const firstDupElement = inputText.find(el => duplicatesSet.has(el));
const searchValue = (_param) => {
for (let i= 0; i < _param.length; i+= 1) {
if (_param.indexOf(_param[i]) === _param.lastIndexOf(_param[i])) return _param[i];
}
return "not founded.";
}
let arr = [1,1,2,2,2,1,3,1,4,4,5]
const dupelearray = (array) => {
let arr2 =[...arr]
let ele = []
let state = false
arr2.map((i,index)=>{
arr2.splice(index,1)
arr.map((j)=>{
return arr2.includes(j) ? null : state=true
})
state && ele.push(i)
state=false
arr2.splice(index,0,i)
})
return console.log(arr.indexOf(ele[0]))
}
dupelearray(arr)
wow i didnt knew lastindexof method and was making this algo so difficult
btw this solution also works but definitely i am new in algo so this will take much more time but the solution still works!!!!!! damn should remember more methods or you have to think so much -_-

How do I search a string in JavaScript array using jQuery? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I have a JavaScript array:
var j_array = new Array();
j_arry=["class:1","division:a","class:5","class:3","division:b","division:c","division:d","class:10"];
I need to find how many times the class is coming and its array key, so I use:
found = $.inArray('class', j_array); ` But it returns `-1`;
Then I use:
var search = 'class';
$.each([j_array], function(index, value){
$.each(value, function(key, cell){
if (search.indexOf(cell) !== -1)
console.log('found in array '+index, cell);
});
});
But that is also wrong. How do I solve this?
From this array I want to get the following:
Class coming 4 times, at key 0, 2, 3, and 7
I want to make a separate array of class only, that is,
new_array = ["class:1", "class:2", "class:3", "class:10"];
Currently there are four classes in j_array. How can I get the Nth class value
That is, 1st class value ="class:1", 2nd class value="class:5", etc.
You could filter elements which match in a new array and just return the length of this new array
var j_arry = ["class:1","division:a","class:5","class:3","division:b","division:c","division:d","class:10"];
var res = j_arry.filter(x => x.includes("class"));
var key = res.map(x => x.split(":")[1]);
console.log("Class coming " + res.length + " , at key " + key.join(","));
console.log("new array = ", res);
Use Array.prototype.filter to filter out the elements of the array that contains the string class - see demo below:
var j_array =["class:1","division:a","class:5","class:3","division:b","division:c","division:d","class:10"];
var result = j_array.filter(function(e){
return e.indexOf('class')!==-1;
});
console.log(result);
EDIT:
To get the list of indexes too, you can try this:
var j_array =["class:1","division:a","class:5","class:3","division:b","division:c","division:d","class:10"];
var filteredIndices = []
var filtered = j_array.filter(function(e,i){
if(e.indexOf('class')!==-1) {
filteredIndices.push(i);
return true;
} else {
return false;
}
});
console.log(filtered);
console.log(filteredIndices);
// Nth class value
console.log(filtered[2]); // this prints the 3rd one
.as-console-wrapper{top:0;max-height:100%!important;}
Here is the answer to your questions 1 + 2. It is also 'n' proof so answers your part 3 also. This works by old-fashioned hard graft rather than funky functions. The original array entries are split and filtered then if qualifying we store in an associative array (results) using a pointer array (list) to make it easier to give a sorted result and pull the values from the associative array. The max variable is probably not necessary but included for clarity - could have used list.length instead. Note that the list[] array will be sparse (missing steps) so we test each entry before use in the output steps.
var j_array = new Array();
j_arry=["class:1","division:a","class:5","class:3","division:b","division:c","division:d","class:10","class:1"];
var a, result = [], list=[], max = -1
for (var i =0; i < j_arry.length; i = i + 1) {
var a = j_arry[i].split(":")
if ( a[0] === "class") {
var key = "c" + a[1]
if ( !result[key] ) { result[key] = {pos:[]}}
result[key].cnt = result[key].cnt ? result[key].cnt + 1 : 1;
result[key].pos.push(i)
list[parseInt(a[1])] = "c" + a[1]
max = parseInt(a[1]) > max ? a[1] : max;
}
}
// say locations
for (var i = 0; i < max; i = i + 1) {
if (list[i]) {
key = "c" + i
console.log("Class " + i + " occurs at " + result[key].pos.toString() )
}
}
// make new array
var newArray=[]
for (var i = 0; i < max; i = i + 1) {
if (list[i]) {
newArray.push("Class:" + i)
}
}
console.log("New array=" + newArray.toString() )
Results are:
Class 1 occurs at 0,8
Class 3 occurs at 3
Class 5 occurs at 2
New array=Class:1,Class:3,Class:5
Single reduce is sufficient here.
var arr = ["class:1","division:a","class:5","class:3","division:b","division:c","division:d","class:10"],
res = arr.reduce((p,c) => c.includes("class") ? (p.count++, p.keys.push(c.split(":")[1]), p)
: p ,{count:0, keys:[]});
console.log(res);
You can use the filter and map functions to filter your array to have only elements that match the text 'class', and use array index notation to access the nth element in the array. Check the below code snippet I hope it will be of help to you.
The below code snippet uses ES6 arrow syntax.
var arr = ["class:1", "division:a", "class:5", "class:3", "division:b", "division:c", "division:d", "class:10"];
var result = arr.filter(x => x.indexOf('class') !== -1);
var indices = result.map(x => arr.indexOf(x));
console.log(indices);
console.log(result);
var nValue = window.prompt('Enter n value');
console.log(result[nValue]);
If you're using jQuery to support some really old browser that still don't implement the new Array functions, and you don't want to polyfill those because you're already using jQuery, then you can use the jQuery equivalents:
var arr = ["class:1", "division:a", "class:5", "class:3", "division:b", "division:c", "division:d", "class:10"]
var result = $.grep(arr, function (x) { return x.indexOf('class') !== -1 })
var indices = $.map(result, function (x) { return arr.indexOf(x) })
This is the same code as this answer, but using jQuery.
You have to do map first then filter.
var j_array = ["class:1", "division:a", "class:5", "class:3", "division:b", "division:c", "division:d", "class:10"];
var result = j_array.map(function(e, i) {
return e.indexOf('class') > -1 ? '' + i : false;
}).filter(function(e) {
return !!e;
});
console.log(result);

Categories