Answers for "Get the last item of Array Set Map object js"

1

get last item in map javascript

row.map((rank, i, arr) => {
    if (arr.length - 1 === i) {
        // last one
    } else {
        // not last one
    }
});
Posted by: Guest on November-04-2020
0

Get the last item of Array Set Map object js

const lastItem = (list) => {
  if (Array.isArray(list)) {
    return list.slice(-1)[0];
  }

  if (list instanceof Set) {
    return Array.from(list).slice(-1)[0];
  }

  if (list instanceof Map) {
    return Array.from(list.values()).slice(-1)[0];
  }

  if (!Array.isArray(list) && typeof list === "object") {
    return Object.values(list).slice(-1)[0];
  }

  throw Error(`argument "list" must be of type Array, Set, Map or object`);
};

// Usage
const l1 = lastItem(["a", "b", "c"]);
// c

const l2 = lastItem(new Set(["d", "e", "f"]));
// f

const l3 = lastItem(
  new Map([
    ["a", "x"],
    ["b", "y"],
    ["c", "z"]
  ])
);
// z

const l4 = lastItem({ a: "x", b: "y", c: "z" });
// z
Posted by: Guest on August-14-2021

Code answers related to "Get the last item of Array Set Map object js"

Code answers related to "Javascript"

Browse Popular Code Answers by Language