How can I move an array record to 0 index and 0 index record to next index and so on [duplicate] - javascript

This question already has answers here:
Most efficient way to prepend a value to an array
(11 answers)
Closed 2 days ago.
I have a requirement to find specific record from array and move that to first position (0 index) and 0 index should move to next index and so on.
I do not want to remove or duplicate any record from array. This is what I have tried, it gives error splice is not defined
var record = data.find(x => x.CodeLovId == existingGridCellItem);
if (record !== null) {
data.remove(record)
data.splice(0, 0, record);
}
And below code duplicates records and removes existing
var record = data.find(x => x.CodeLovId == existingGridCellItem);
if (record !== null) {
data[0] = record
}
Ex -
arr1 = ['YES', 'NO', 'OK']
Item to move ['NO']
Ans - arr1 = ['NO', 'YES', 'OK']
How can I do it ?

You need indices for manupulating arrays. To get only an item does not work with your code.
Instead
get the index of the wanted item to be moved to top,
check if index is in array and
unshift spliced item.
const
array = [1, 2, 3, 4, 5],
index = array.findIndex(v => v === 4);
if (index !== -1) array.unshift(...array.splice(index, 1));
console.log(array);

You can use splice and unshift, to remove value from the index and to the first position.
const list = [1, 2, 3, 4, 5];
const record = 31;
const index = list.indexOf(record);
if (index !== -1) {
list.splice(index, 1);
list.unshift(record);
}
console.log(list);

Related

Finding the lonely integer - JavaScript [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 8 months ago.
Consider the array [1,2,2]
The array contains two unique values: 1, 2
The array contains duplicate values: 2
The lonely integer is 1
How can the lonely integer be returned?
For an array where you only care about grabbing the first integer which is lonely, you can check if the indexOf and lastIndexOf are the same. If they are, then it's lonely.
const array = [2, 2, 1, 3, 4, 3, 4];
const findLonely = (arr) => {
for (const num of arr) {
if (arr.indexOf(num) === arr.lastIndexOf(num)) return num;
}
return 'No lonely integers.';
};
console.log(findLonely(array));
If you have an array that has multiple lonely values, you can use this method to find all of the lonely values:
const array = [2, 2, 1, 3, 4, 3, 4, 6, 8, 8, 9];
const findAllLonely = (arr) => {
const map = {};
arr.forEach((num) => {
// Keep track of the number of time each number appears in the array
if (!map[num]) return (map[num] = 1);
map[num]++;
});
// Filter through and only keep the values that have 1 instance
return Object.keys(map).filter((key) => {
return map[key] === 1;
});
};
console.log(findAllLonely(array)); // expect [1, 6, 9]
const array = [0,1,2,2,1,5,4,3,4,3,2];
let lonely = array.filter((item,index)=> array.indexOf(item) === array.lastIndexOf(item));
console.log(lonely);
Working Demo :
// Array with duplicates
const arrWithDuplicates = [1, 2, 2];
var result = arrWithDuplicates.sort().filter((x,i,arr) => x !== arr[i+1] && x !== arr[i-1]);
console.log(result); // [1]
For each element your can use .filter() to help count the how many times the element is repeated. Then use .filter() again to return only those elements that appear once.
const nums = [1,2,2,3,4,4,4,5,5,6,7,7,7,8,8];
const singles = nums.filter(
//count how many times each element appears
num => nums.filter(n => n === num)
//return only those with freq. of 1
.length === 1
);
console.log( singles );
//OUTPUT: [ 1, 3, 6 ]
Use a 'for' loop with the filter function to loop through the array and only return the value that appears once
const arr = [0, 1, 2, 2, 1];
let unique;
for(var i = 0; i < arr.length; i++) {
if(a.filter(x => x == arr[i]).length == 1) {
unique = arr[i]
}
}
return unique;
the code below solves the challenge with O(n) complexity
function lonelyinteger(a) {
let result;
a.every((e)=>{
if(a.filter(x=>x==e).length==1) {
result = e;
return false;
}return true;
})
return result;
}
O(n) complexity
function lonelyinteger(a) {
for (let i = 0; i < a.length; i++) {
const count = a.filter((v) => v === a[i]).length;
if (count === 1) {
console.log(a[i]);
return a[i];
}
}
}
If there is multiple unique number in an array = [1,2,3,4,5,3,2,1] here 4 and 5 both are unique ,there is two lonely integer so the output should be like this result = [4,5]. In case of single unique integer we can return the result as result = [3] or result = 3. The below code snippet will solve both the scenario.
const array = [1,2,3,4,5,3,2,1]
let result = []
array.every(e => {
if(array.filter(x => x == e).length == 1) {
result.push(e)
}
return true
})
console.log(result)
Explanation: step by step
Your desire array from where you need to get the lonely integer.
We defined result as an array.
You can use simple for loop or array forEach (learn about forEach).
We are using array filter method (learn about filter) to get our work done. Here array.filter(x => x == e) this will result when the value of e is 1 (first element of the array) then the output will be [1,1].
So for 1 the .length == 1 will return false. This process will continue to get false and the if condition will not get executed until a the 'e' became 4 (4th element of the main array).
When 'e' became 4 then the result of array.filter(x => x == 4) will be [4] so the condition array.filter(x => x == e).length == 1 will be true and the if condition will execute. And inside that we are pushing the value 4 to the result array. You can add a next line return false to stop the execution and you will get only one single lonely integer.
return true is required here only if you're using the every method (learn about array every method)
Play with the code to get better understanding or comment if you've some question about this solution. Please give a up-vote if this answer is helpful.

Get the index of duplicate values except the first

Below is an example array:
const attD = [1, 2, 3, 4, 3, 3]
How can we get the index of the duplicate values from this array? In this example, 3 is repeated thrice. So, I want to get the index 4, index 5 as these are duplicated at that positions (ignoring the first occurrence).
I have tried the below code, but it is giving me values. Instead, I need the index.
const findDuplicates = attD => attD.filter((item, index) => attD.indexOf(item) !== index);
const duplicates = findDuplicates(attD);
console.log(duplicates);
With .map(), add the index of duplicated values into the array. For non-duplicate value, will be added with undefined value [Will be filtered in Step 2].
With .filter(), remove the value which is undefined from the array.
const attD = [1, 2, 3, 4, 3, 3];
const findDuplicates = attD => attD.map((item, index) => {
if (attD.indexOf(item) !== index)
return index;
}).filter(x => x); // Equivalent to .filter(x => x != undefined || x != null)
const duplicates = findDuplicates(attD);
console.log(duplicates);

How do I remove an item from an array by value but keep the original index order? [duplicate]

This question already has answers here:
Javascript Array Splice without changing the index
(5 answers)
Closed 5 years ago.
How do I remove an item from an array by its value, but still keep the index order instead of the array re-indexing the items?
To be clearer, the following code will remove the item by value, but it will re-index the values too meaning that 15 will have an index of 0 instead of 1 after we splice 5 out.
var arr = [5, 15, 110, 210, 550];
var index = arr.indexOf(5);
if (index > -1) {
arr.splice(index, 1);
}
If you want to keep the index instead of slicing set the index value to undefined...
var arr = [5, 15, 110, 210, 550];
var index = arr.indexOf(5);
if (index > -1) {
arr[index] = undefined;
}
console.log(arr);
arr.forEach(function(item){
if(item !== undefined){
console.log(item);
}
});
you can always iterate, with the conditional filtering the undefined values..

How to return previous and next element by element from array in JavaScript?

I have an array and i want to return the next and previous elements by a given string.
This is the array:
var array = [
"11111",
"22222",
"343245",
"5455",
"34999",
"34555",
];
The user inputs a random number, unknown number, and i have to find the next and previous elements based on the user' string.
For example the User writes: 3499
And the return must be Previous element is 5455 and next element is 34555.
Use Array#indexOf method to get the index of the element and get other element based on the index.
var array = [
"11111",
"22222",
"343245",
"5455",
"34999",
"34555",
];
var ele = "34999";
var index = array.indexOf(ele);
console.log('next', array[index + 1])
console.log('prev', array[index - 1])
Using "indexOf":
function getNextIten(num, nums){
const idx = nums.indexOf(num)
if (idx && idx < nums.length-1){
return nums[idx+1]
}
return null
}
nums = [5, 3, 7, 8, 1, 10];
num = 7;
console.log(getNextIten(num ,nums)) //8
Or in one line like:
prev = nums.find((_, i, e) => num === e[i + 1]);
next = nums.find((_, i, e) => num === e[i - 1]);

JavaScript Arrays : Keep only values that are present an odd number of times, including once

Hey guys so for example I have an array:
myArray[5,4,1,2,1,4,5,6,7,8,9,10,1,2,1,5,3,2]
I'm sorting that array:
[1, 1, 1, 1, 10, 2, 2, 2, 3, 4, 4, 5, 5, 5, 6, 7, 8, 9]
And I want to delete only the two duplicates so the array I want will be
[10,2,3,5,6,7,8,9]
So i'm using splice:
for (var index = 0; index < myArray.length +1; ++myArray) {
if(myArray[index+1]== myArray[index]) {
myArray.splice(index);
myArray.splice[index+1];
}
}
But when I'm pushing more of the of the numbers, the results seem unpredictable
How to do this properly?
To clarify: The purpose is to eliminate the numbers which repeat an even number of times.
Here's another method, which checks for an odd number of elements by subtracting the indexOf the key from the lastIndexOf the key after sorting:
var myArray = [5,4,1,2,1,4,5,6,7,8,9,10,1,2,1,5,3,2];
var result = myArray.sort().filter(function(key, idx) {
return myArray.indexOf(key) === idx && //handle first instance only
(myArray.lastIndexOf(key) - myArray.indexOf(key)) % 2 === 0;
});
console.log(result);
Here is an ECMAScript2015 solution:
var myArray = [5,4,1,2,1,4,5,6,7,8,9,10,1,2,1,5,3,2];
var count = myArray.reduce((count, num) =>
(count[num] = (count[num] || 0) + 1, count), {});
myArray = Object.keys(count).filter(num => count[num] % 2).map(Number);
console.log(myArray);
The count variable is an object of which the properties are the numbers in the original array. The value for each of these properties is the number of occurrences of that number in the original array.
The keys are then iterated to get only those into the final array that have a value (i.e. occurrences) that is odd. As object properties are iterated in numerical order (when numerical), the result is automatically sorted numerically.
About your code:
The for loop you have, has some issues:
for (var index = 0; index < myArray.length +1; ++myArray) {
if(myArray[index+1]== myArray[index]) {
myArray.splice(index);
myArray.splice[index+1];
}
}
Certainly you don't want to increment myArray, but index.
The boundary condition should not be length+1 but length-1 as in the body you have myArray[index+1] and don't want to go out of bounds there.
But more importantly, doing splice in your for loop will make the elements shift position, and as you then still increment index, you will skip elements.
In short, you should not use splice in such a loop. You can solve this by going in the reverse direction, and start at the end of the array working towards the beginning.
But the above proposed code does not have this problem and also saves you the step of sorting.
You can do this with two reduce and Object.keys(). First add values to object and then check each value with % 2 and add to array.
var myArray = [5,4,1,2,1,4,5,6,7,8,9,10,1,2,1,5,3,2];
var obj = myArray.reduce(function(o, e) {
o[e] = (o[e] || 0)+1;
return o;
}, {})
var result = Object.keys(obj).reduce(function(r, e) {
if(obj[e] % 2) r.push(Number(e));
return r;
}, []);
console.log(result)

Categories

Resources