Remove first occurence of an element using JavaScript or Lodash - javascript

I have an array like this -
["a", "a", "b", "c", "d", "e"]
I want to operate on this and filter it to remove only the first occurence of every element in the array.
The output in the above case is expected to be - ["a"]
How can I achieve this using JavaScript or Lodash?

By wanting the first one of duplicate following items, you could use Array#lastIndexOf along with a check of the actual index.
const
data = ["a", "a", "b", "c", "d", "e"],
result = data.filter((v, i, a) => i !== a.lastIndexOf(v));
console.log(result);

You can use an empty object as a map to easily check if the item has been found before and then use Array#filter to remove the ones you don't want.
var list = ["a", "a", "b", "c", "d", "e"];
var occurences = {};
var filteredList = list.filter(function(item) {
if (item in occurences) return true; // if it has already been registered, add it to the new list
occurences[item] = 1; // register the item
return false; // ignore it on the new list
});
console.log(filteredList);
Shorthand version
let list = ["a", "a", "b", "c", "d", "e"], occurences = {};
list = list.filter(item => item in occurences ? 1 : occurences[item] = 1 && 0);
console.log(list);

you can simply use shift method checkout it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift

Related

How does one merge and compute array items within a nested array structure via a fixed condition/rule

I have an JavaScript heterogenous array of arrays which looks like :
let bigArray = [["A", "B", 221.67],["C", "B", 221.65],["B", "D", 183.33],["B", "A", 4900],["E", "B", 150],["A", "B", 150]]
Now i want to add the 3rd element(number) if the first and second elements matches with the first and second element of next array(in multidimensional array), then add 3rd element(number) of both array & also perform minus operation if reverse of those elements match is found.
Output will be:
let ans = [["B", "A", 4528.33],["C", "B", 221.65],["B", "D", 183.33],["E", "B", 150]]
sub array ["B","A", 4528.33] is formed by performing minus operation, i,e 4900-221.67-150
In bigArray there are array with repeated pair of elements like "A" & "B"(in single sub array). So for all matching subarrays perform sum operation & if reverse of that matching sub array is found then perform minus operation. i,e=> 4900-221.67-150
I tried many methods but cant able to achieve the desired output for all the cases. Any help will be appreciated, Thanks
You could group with sorted keys to maintain a standard key and check if the part keys have the same order, then add the value or subtract.
If a value is negative change the keys and take a positive value.
let data = [["A", "B", 221.67], ["C", "B", 221.65], ["B", "D", 183.33], ["B", "A", 4900], ["E", "B", 150], ["A", "B", 150]],
result = Object.values(data.reduce((r, [a, b, v]) => {
const key = [a, b].sort().join('|');
if (r[key]) {
r[key][2] += a === r[key][0] ? v : -v;
if (r[key][2] < 0) r[key] = [r[key][1], r[key][0], -r[key][2]];
} else {
r[key] = [a, b, v];
}
return r;
}, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sort an array of strings based on an array of numbers: Another version (Not duplicate!!) [duplicate]

This question already has answers here:
Reorder the objects in the array
(5 answers)
Closed 2 years ago.
I know I uploaded a similar question, but my intention is different here so this is not a duplicate question.
I want to sort an array based on another array of numbers. More specifically, if 1 is the nth element of the array of numbers, I want to rearrange the target array so that the nth element in the original array is the first element, and so on. For example;
//Case 1
const input = ["a", "b", "c", "d", "e"];
const order = [2, 4, 5, 1, 3];
intended_result: ["d", "a", "e", "b", "c"];
//Case 2
const input = ["a", "b", "c", "d", "e"];
const order = [3, 1, 4, 5, 2];
intended_result: ["b", "e", "a", "c", "d"];
What would be the Javascript code to do the above operation? Any suggestion?
Thanks a lot in advance!
No need for sorting, you just need to apply the permutation that you have:
const result = [];
for (let i=0; i<order; i++)
result[order[i]-1] = input[i];
This should be working:
const sorted = input.slice().sort((a, b) => {
const indexA = input.indexOf(a);
const indexB = input.indexOf(b);
return order[indexA] - order[indexB];
});
We slice the input so it won't be mutated and change the index of values in the array.

JS Array not selecting correct values

I am trying to select items from array using slice() method but it is not selecting right values.
var alphabets = ["A", "B", "C", "D", "E"];
var show = alphabets.slice(1, 2);
console.log(` ${show} `);
It should output B, D but it is giving only: B
Array starting from zero B is 1 and from end D is 1
In other example.
var alphabets = ["A", "B", "C", "D", "E"];
var show = alphabets.slice(1, 3);
console.log(` ${show} `);
Above code output: B,C
How this is even selecting elements?
The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument.
var alphabets = ["A", "B", "C", "D", "E"];
var show = alphabets.slice(1, 3);
console.log(` ${show} `);
Take your example, "D" is at position 3 so it will not include "D" in your output. It will only give "B" and "C" in your output.
The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.
arr.slice([begin[, end]])
begin Optional
Zero-based index at which to begin extraction.
end Optional
Zero-based index before which to end extraction. slice extracts up to but not including end.
var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
If you have questions about JavaScript the Mozilla Developer Network (MDN) is a great place to go.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
This is the working principle of slice:
slice(start,end)
start is the start index and it starts from 0.
end is the end index, but does not include
In your case:
A ---> index 0
B ---> index 1
C ---> index 2
D ---> index 3
E --->index 4
Thus, slice(1,2) will return only index "1" which is B
Please refer to the documentation of Array.prototype.slice, as you have not used the second argument correctly.
The slice() method returns a shallow copy of a portion of an array
into a new array object selected from begin to end (end not included).
The original array will not be modified
Refer to MDN/JS/Array/slice
slice() returns a copy of the array starting for the first index until a second index (NOT INCLUDED). If you want to start counting from the end on the second value you must use a negative index.
var alphabets = ["A", "B", "C", "D", "E"];
var show = alphabets.slice(1, 3);
console.log(` ${show} `);
This will display BC
as well as:
var alphabets = ["A", "B", "C", "D", "E"];
var show = alphabets.slice(1, -2);
console.log(` ${show} `);
The slice() method returns the selected elements in an array, as a
new array object.
The slice() method selects the elements starting at the given start
argument, and ends at, but does not include, the given end argument.
see the below example with same array.
var alphabets = ["A", "B", "C", "D", "E"];
console.log(alphabets .slice(2));
// expected output: Array ["C", "D", "E"]
console.log(alphabets .slice(2, 4));
// expected output: Array ["C", "D"]
console.log(alphabets .slice(1, 5));
// expected output: Array ["B", "C", "D", "E"]

Javascript some() method and additional parameter

I need to check if at least one element in an array pass a condition.
The condition depends on a variable.
For example, I'm using something like this:
function condition(previousValue, index, array) {
return additonalValue.indexOf(previousValue) + previousValue.indexOf(additonalValue) < -1;
}
I can't figure out how can I pass the "additonalValue" parameter to the array.some(condition) expression.
I'm using jQuery so, an alternative for it is welcome.
Is there a way to pass a parameter to array.some() method?
If you want to pass an additional parameter to the function that is placed inside the some method you can use bind.
var myArray = ['a', 'b', 'c', 'd'];
var otherValue = 'e';
function someFunction(externalParameter, element, index, array) {
console.log(externalParameter, element, index, array);
return (element == externalParameter);
}
myArray.some(someFunction.bind(null, otherValue));
This would give you:
e a 0 ["a", "b", "c", "d"]
e b 1 ["a", "b", "c", "d"]
e c 2 ["a", "b", "c", "d"]
e d 3 ["a", "b", "c", "d"]
false
Using a closure looks like the simplest solution :
var additonalValue = 79;
var r = myArray.some(function(previousValue) {
return additonalValue.indexOf(previousValue) + previousValue.indexOf(additonalValue) < -1;
});
The some() function accepts additional arguments in the form of an array, that is set to this inside the callback, so you could pass a number of values that way :
var arr = ['one', 'two', 'three'];
var val = 'two';
var r = arr.some(function(value) {
return this[0] == value;
}, [val]);
FIDDLE

Join Array from startIndex to endIndex

I wanted to ask if there is some kind of utility function which offers array joining while providing an index. Maybe Prototype of jQuery provides this, if not, I will write it on my own :)
What I expect is something like
var array= ["a", "b", "c", "d"];
function Array.prototype.join(seperator [, startIndex, endIndex]){
// code
}
so that array.join("-", 1, 2) would return "b-c"
Is there this kind of utility function in an pretty common Javascript Library?
Regards
globalworming
It works native
["a", "b", "c", "d"].slice(1,3).join("-") //b-c
If you want it to behave like your definition you could use it that way:
Array.prototype.myJoin = function(seperator,start,end){
if(!start) start = 0;
if(!end) end = this.length - 1;
end++;
return this.slice(start,end).join(seperator);
};
var arr = ["a", "b", "c", "d"];
arr.myJoin("-",2,3) //c-d
arr.myJoin("-") //a-b-c-d
arr.myJoin("-",1) //b-c-d
Just slice the array you want out, then join it manually.
var array= ["a", "b", "c", "d"];
var joinedArray = array.slice(1, 3).join("-");
Note: slice() doesn't include the last index specified, so (1, 3) is equivalent to (1, 2).

Categories

Resources